texts: Procedural river or road generation for infinite terrain

texts:
I should say paths, not roads as I'm thinking more medieval-like. Also, not looking for realism. The answer I'm looking for will be to fit into the mold I describe rather than realism.

I am looking for a method to generate procedural roads/rivers in a curvy sort of fashion, but I'm wanting to do so for a infinite terrain type system. Just like how perlin noise generates blobs, I'm wanting to generate random length line segments (possibly infinite length).

I'm aware of strategies like the suggested answer found here, however it relies on a specified start and end point to work, I don't have a specified start and end point. I'd like to be able to simply call a function using arbitrary coordinates and have it return whether the specific coordinates are part of the river/road.

I am not wanting to require terrain to be generated in advance. That includes a heightmap (like used for rainfall simulations or similar). I would also not want to require a start/end point.

Is there such an algorithm or tweak to a noise algorithm someone might know of to accomplish what I'm trying to explain?

The closest I've came to so far is multi-ridged fractals, if I'm using the name properly. I'm just taking the absolute value of value noise (assuming it is scaled to -1 to +1) and setting a threshold. My primary issue with this is the lines overlap way too often, are mostly circular, sometimes converge to form large lakes which is neat but undesired, and often times the thickness of the lines vary too much.

Here's a picture of what I have so far in 2D, but at a very high frequency to show more detail:


texts: Unity toggleable shader property misbehaves when set by code?

texts:
I've added a toggle to my shader:

[Toggle(ENABLE_COLOR_BLEND)] _EnableColorBlend ("Enable Color Blend", Int) = 0

In the Subshader:

#pragma shader_feature ENABLE_COLOR_BLEND

And in the fragment shader:

#ifdef ENABLE_COLOR_BLEND
    color = lerp(_DryColor, _WetColor, _ColorBlend);
#endif

And there it is in the inspector, and when I toggle it, color blending is turned on and the material is rendered as it should be. if I turn it off, it's off.

But if I try to set it like this in code:

Renderer.material.SetInt("_EnableColorBlend", 1);

The material is rendered like if EnableColorBlend is off.

In the inspector it's ticked, and as soon as I turn it off, it gets ticked again. (I set it in an Update) But for some reason, it's still rendered like color blending is off.

And if I remove the SetInt above, and set it by hand, everything works fine.

Why?

Idea: If I set it by hand, there is a smooth transition (don't know why) instead of an instant change in shade.
Maybe by setting it constantly to 1, it always just starts the transition, but can't finish it?

EDIT: Just checked it with a guard, and it still behaves the same.

if (Renderer.material.GetInt("_EnableColorBlend") == 0) Renderer.material.SetInt("_EnableColorBlend", 1);


texts: How to calculate/structure/define rotation vector for OpenGL / WebGL

texts:
I am trying to define the buffer data for WebGL and want to have in there something that encodes the fact that an object might be rotating. So it makes me think of angular momentum. So if you have something like that, like the angular momentum or some other rotation "vector" or something, you could use that to calculate a rotation matrix, and then go from there.

The problem is I don't know what that rotation thing is, angular momentum or something else. I keep searching rotation vector, but I'm not sure that's it. Wondering if you have any suggestions on how to have rotation encoded (the rotation force), before it is in a matrix form. This is just for 2D rotation.


texts: How to turn off antialiasing in Graphics class?

texts:
I have been using the following code with a Graphics2D buffered image

g.setRenderingHint(
  RenderingHints.KEY_INTERPOLATION,
  RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

to ensure the image looks correct when scaled in.

If I use the Graphics class instead of Graphics2D it appears to auto anti-alias and present a zoomed image as blurred.

Is there a way to turn off anti-aliasing with the Graphics class so I do not have to use the Graphics2D class?


texts: How can I remove enemies from my ArrayList after they have died?

texts:
Possible Duplicate:
  How do I best remove an entity from my game loop when it is dead?

Right now, I have an ArrayList like this:

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

When an enemy dies, how can I remove it? Should I use a different type of list, array, or set?


texts: Ray Tracing Shadows in deferred rendering

texts:
Recently I have programmed a raytracer for fun and found it beutifully simple how shadows are created compared to a rasterizer. Now, I couldn't help but I think if it would be possible to implement somthing similar for ray tracing of shadows in a deferred renderer. The way I though this could work is after drawing to the gbuffer, in a separate pass and for each pixel to calculate rays to the lights and draw them as lines of unique color together with the geometry (with color 0). The lines will be cut-off if there is occlusion and this fact could be used in a fragment shader to calculate which rays are occluded.

I guess there must be something I'm missing, for example I'm not sure how the fragment shader could save the occlusion results for each ray so that they are available for pixel at the ray's origin. Has this method been tried before, is it possible to implement it as I described and if yes what would be the drawbacks in performance of calculating shadows this way?


texts: Saving player's progress in a Unity game

texts: I am making a game using the Unity game engine. I want to save the player's progress including level, experience points, chosen character, etc. Presently I am using playerprefs but I want to know whether this will work for gamers who will run this game on their mobile devices (Android/iOS) as well as desktops (OSX/PCs)? If not, then how should I save this information? I want to auto-save player progress after clearing each stage.


texts: I'm Dragging object by using touch (mobile) it doesn't stop when hit collider

texts:
I want to make object stopped when it hit collider of another object.
But it doesn't stop. How can I fix this? - Unity

my code is:

public class move: MonoBehaviour {
    public float speed = 0.5f;
    // Update is called once per frame
    void Update () {
      if (Input.touchCount ==1)
        {
            Touch touch = Input.GetTouch(0);
            float x = -7.5f + 15 * touch.position.x / Screen.width;
            float y = -2;
            transform.position = new Vector2(x * speed, y);
        }
    }
}


texts: I have seen the term a few times (e.g. here). I tried looking it up but did not find much information. I thought it would be something like parallax-scrolling, but I have seen suggestions otherwise (e.g. here). What is the difference?


texts: Terrain Generation - Only draws first sprite and last row on the X axis

texts:
So, I have a problem where I'm trying to loop trough columns of sprites, that later will be drawn to fill a specific area.

But it only renders the first sprite and the last row of sprites on the X axis.

Like this :

As you see it doesn't fill the entire "screen".

This is how I try to loop trough all the sprites and draw them :

void EntityManager::GenerateMap(float xSize, float ySize, int texture)
{
    // Generates a series of rooms connected so eachother with random positions and size.
    Random randomGen;

    roomTextures.push_back(sf::Texture());

    if (!roomTextures[texture].loadFromFile("Resource/Images/Test.png"))
        std::cout << "Failed to load texture from file." << std::endl;
    else
    {

        for (int y = 0; y < ySize; y++)
        {
            std::cout << "y : " << y << std::endl;
            for (int x = 0; x < xSize; x++)
            {
                std::cout << "x : " << x << std::endl;
                roomSprites.push_back(new sf::Sprite());
                roomSprites[x]->setPosition(sf::Vector2f(x * 32, y * 32));
            }
        }

        std::cout << roomSprites.size() << std::endl;

        for (int i = 0; i < roomSprites.size(); i++)
        {
            roomSprites[i]->setTexture(roomTextures[texture]);
            //std::cout << "x : " << roomSprites[i]->getPosition().x << " y : " << roomSprites[i]->getPosition().y << std::endl;
        }
    }

}

Where xSize = 10, and xSize = 10 and texture = 0.

And here's the "definitions" of the array list things :

std::vector<sf::Sprite*> roomSprites;
std::vector<sf::Texture> roomTextures;

Update :

So, I tried looping trough the sprite positions which resulted in this :

There were more positions below those, all of them being x: 0 y: 0


texts: Offsetting image position when scaling in XNA

texts:
What Im trying to do is pretty simple, offset the rendering position of my image when scaled up/down. I honestly can't remember how to-do this :(

if (newAnim.texture != null)
{
    // Set Source Rectangle
    sourceRect.X = newAnim.imageRectArray[newAnim.CurrentFrame].X;
    sourceRect.Y = newAnim.imageRectArray[newAnim.CurrentFrame].Y;
    sourceRect.Width = newAnim.imageRectArray[newAnim.CurrentFrame].Width;
    sourceRect.Height = newAnim.imageRectArray[newAnim.CurrentFrame].Height;

    // Get new center when scaled.
    Vector2 center = new Vector2(
        (newAnim.imageVector2Array[newAnim.CurrentFrame].X * scale) / 2,
        (newAnim.imageVector2Array[newAnim.CurrentFrame].Y * scale) / 2
    );

    // Only Render if we have Something to use
    if (newAnim.CurrentFrame >= 0)
        spriteBatch.Draw(
            newAnim.texture, new Vector2(100, 100), sourceRect,
            Color.White, 0f, center, 1f, SpriteEffects.None, 0f
        );

I'm unsure what I need to do to the Vector2. Hopefully getting the center/origin position is correct? I think so.

Edit:

http://dl.dropbox.com/u/13874083/screenshots/screen120107-160918.png

The bigger image is the scaled image (pretty obvious :P), but both are rendered at 100, 100.


texts: How can I store tile maps as PNG images?

texts:
I want to let players of my top-down game save, load and share worlds as PNG images. How do I read the colors in a PNG file or change them?

I imagine something like this:

BufferedImage mapImg = ImageLoader.loadImage(path);

// (then, later)

for(x = 0; x < mapImg.width; x++) {
    for(y = 0; y < mapImg.height; y++) {
        // Look up the color at this position
    }
}

Here is my ImageLoader class:

public class ImageLoader {

    public static BufferedImage loadImage(String path) {
            try {
                return ImageIO.read(ImageLoader.class.getResource(path));
            } catch (IOException e) {
                e.printStackTrace();
                 System.exit(1);
            }
            return null;
    }
}


texts:
I apologize in advanced if this is a trivial ask, but I am wondering if it is possible to use an animation to change the color of a Text element from teal -> white without any lerp, i.e the color instantly changes. My current animation is only the one frame at 0:00 where I do the switch, but you can still see that the color is lerping even though it is the first and only frame. Am I missing something simple or should I just script the change? Fixing the problem is easy (Trivial to script), but I am just curious if there is something in the animation I can change to not have the color lerp?

I posted the question here as well, but I never have any luck posting on the Unity forums.


texts:
This is the first time I am working with particles (GL_POINTS) I am using kinematic equations and controlling their movement in vertex shader.

I am following an example given in OpenGL 4.0 Cookbook by David Wolff.

I am not able to see the texture which I am loading in the particle.
However, I can see the texture if I put it to some other object, say quad.

I have increased the size of POINT using glPointSize just so I can see if the texture is really visible.

In the image above you can that I am loading and rendering the same texture for quad, but when I use the same texture for particles, I get different results.
PS: The color which you're seeing for the particles is from the texture itself. If i choose a texture having white color, the same is seen for the particles.

Here is a code from my fragment shader.
I figured if the texture is being displayed correctly for quad, then the issue may not be with the loading of the texture.

if(rendPlane == false)
{
    //vs_fragColor = vec4(.3f,.3f,0.6f,1.00f);
    vs_fragColor = texture(u_particlesTex, gl_PointCoord);
    vs_fragColor.a *= vs_transp;
}
else
{
    //plane...
    vs_fragColor = texture(u_particlesTex, vs_texCoord);
}


texts:
I'm currently given the task to design & create a simple decal-system in C++/DirectX.

Does anybody know a great tutorial, article or paper to start with? (Especially the part about 2D-texture to 3D-surface projection and clipping isn't entierly obvious to me.)

I'd also appreciate just simple hints and best-practices.


texts:
I wanted to implement a directional light system in my game, and instead of passing the direction to the light, I chose to use an angle, and only later convert it to a directional vector, so it is a bit more easier, to manage.

I tried to search on the internet for a good solution to this conversion, but the answers I found said different things (Like this one and this one), and not always in understandable form (like using pitch, yaw and roll incorrectly). One of them said to use a format like

x = sin(roll) * sin(yaw)
y = sin(roll) * cos(yaw)
z = sin(yaw)

An other one used something like

x = cos(yaw) * cos(pitch)
y = cos(yaw) * sin(pitch)
z = sin(pitch)

So my question is:

What is the correct way to transform Euler angles (Tait-Bryan version) into a Directional vector?


texts: I'll keep it short. How does one achieve the effect depicted in the image below? Is it feasible to do in realtime? It looks deceptively simple, but it probably isn't. Are there any keywords I can search for to get more information about programming the shaders to achieve this look? Thanks.


texts: XNA - Getting HLSL pixel of current render target?

texts:
I'm setting a render target in XNA using the following lines of code:

        Game.GraphicsDevice.SetRenderTarget(physicsTexture);
        Game.GraphicsDevice.Clear(Color.White);

        noiseEffect.CurrentTechnique.Passes[0].Apply();

        DrawQuad();

        Game.GraphicsDevice.SetRenderTarget(null);

        physicsTexture.GetData<Color>(physicsBuffer);

Now, physicsTexture is a RenderTarget2D. This texture already has some of its pixels colored by the CPU before it gets set as the render target.

So when my pass in the HLSL pixel shader runs, my question is: Can I get the current pixel color of a given texture coordinate using tex2D or something similar on the render target, before drawing a new pixel at that area?


texts: Algorithms for rainfall + river creation in procedurally generated terrain

texts:
I've recently become fascinated by the things that can be done with procedurally terrain and have started experimenting with world building a bit. I'd like to be able to make worlds something like Dwarf fortress with biomes created from meshing together various maps.

So first step has been done. Using the diamond-square algorithm I've created some nice hieghtmaps. Next step is I would like to add some water features and have them somewhat realistically generated with rainfall. I've read about a few different approaches such as starting at the high points of the map, and "stepping" down to the lowest neighboring point, pooling/eroding as it works its way down to sea level.

Are there any documented algorithms with this or are they more off the cuff?

Would love any advice/thoughts.


texts: GJK point-in-tetrahedron - capping the number of searches?

texts:
The very informative mollyrocket video has given me quite a lot to work with, but one thing that the video seems to suggest is that the algorithm should ideally run until it definitely determines whether or not there's a hit.

I was of the idea that if there's no collision, it would be obvious by testing the dot product of the latest point against the search direction; if it is not positive, then we did not pass the origin, so a tetrahedron which encloses the origin simply cannot be built.

In cases where there is a hit OR a clear miss, the routine typically picks up less than 11 loops through. However, as I tend towards 'questionable territory' and the definitive hit/miss is visually less distinct, there are times when the method apparently continues to pass the origin yet construct unsuccessful simplexes.

Is it common to cap this kind of function at a max number of tries? Right now I am somewhat arbitrarily using the number of points in one shape times the number of points in the other shape; in other words:

max_tries = len(shape1.pts) * len(shape2.pts)

It feels a bit hacky and I have to assume that the routine is geared towards simply running ad nauseum until it smacks into a clear hit/miss situation.

Has anyone experienced this before? Is this a problem or an anticipated safety measure in such an algorithm? If it needs to be done I'll gladly share some code, but I think it stands as self-evident that it is kind of a longer read than most code snippets so I've abstained for now.


texts:
I'm not new to programming, but I am relatively new to game programming. I am trying to create a version of Breakout, as a good basic game to get myself introduced to 2d game programming.

I currently have a class structure as the following:

The BreakoutRunner class is the basic initialization stuff for a JFrame. It holds a BreakoutView, which is a JPanel that contains the update logic, and the renderer.

First off, is this a correct structure?

Secondly, I am having problems getting this to work correctly. In BreakoutView, I have the following constructor:

public BreakoutView()
{
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setBackground(Color.black);

    state = GameState.PLAYING;

    gameBlocks = new Block[NUM_ROWS][BLOCK_ROWS];
    gameBall = new Ball(WIDTH / 2, HEIGHT /2);
    player = new Player(WIDTH / 2);

    initializeGrid();

    //start();
}

I have the method start() which is commented because it is causing the problems. With the line commented, the game looks like so:

But the problem arises when I take away the comment, and add the start() method.

The start method:

private void start()
{
    while(state == GameState.PLAYING)
    {
        update();
        repaint();

        try
        {
            Thread.sleep(50);
        }
        catch(InterruptedException e)
        {
            assert(e == null);
        }
    }
}

Which includes calls to update:

private void update()
{
    checkBlocks();
    moveBall();
}

and repaint, which I believe calls the paintComponent method:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    drawWalls(g);
    drawBlocks(g);
    drawPlayer(g);
    drawBall(g);
}

When the code is run with start() uncommented, it gets thrown into an infinite loop, while the frame and the panel get turned into something that looks like this:

What is going on here? Any idea why I'm just sent into an infinite loop?

Thanks Everyone!

DISCLAIMER: I know the update loop is not completely correct. I am more worried about getting it to work period, rather than at an even frame rate... (IE. sleep == bad).


texts: Could you explain this calculation of tiling and offset?

texts:
I don't understand why we add +colNumber when we calculate the offset = Vector2 ((uIndex+colNumber) * size.x, which gives us x=3 for the index 13, which is the square located at the coordinates x:1, y:0 on the image (one square to the right, and "v" starts from the bottom). If the UV of the big image is on [0,1] for U and for V, why do we reach 3 for uIndex? And why don't we only do :

u = uIndex * sizeUV.x = 1 * 0.25 = 0.25
v = vIndex * sizeUV.y = 0 * 0.25 = 0

Here is the code from http://wiki.unity3d.com/index.php/Animating_Tiled_texture_-_Extended :

// Calculate index
var index : int = Time.time * fps;
// Repeat when exhausting all cells
index = index % totalCells;

// Size of every cell
var size = Vector2 (1.0 / colCount, 1.0 / rowCount);

// split into horizontal and vertical index
var uIndex = index % colCount;
var vIndex = index / colCount;

// build offset
// v coordinate is the bottom of the image in opengl so we need to invert.
offset = Vector2 ((uIndex+colNumber) * size.x, (1.0 - size.y) - (vIndex+rowNumber) * size.y);

renderer.material.SetTextureOffset ("_MainTex", offset);


texts: Play continuous music when swapping between multiple scene in Unity3d

texts:
I have the following scenario

Main menu scene containing a gameobject with an audio source component
An about us scene

gameObject script :

using UnityEngine;
using System.Collections;
public class ManageMusic : MonoBehaviour {

// Use this for initialization
    void Start () {

}

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

}
public static ManageMusic Instance;
void Awake()
{

    if (Instance)
        DestroyImmediate (gameObject);
    else {
        DontDestroyOnLoad (gameObject);
        Instance = this;

    }
  }
}

when i click on aboutUs Button the Game Music object keep on playing an i can hear the music but when i return back to the main menu no music is still playing . i can see that the gameobject is not destroyed when i return to the main menu and the audio Listener have the value of the volume set to 1 , but i can't figure out the problem can anyone help me


texts: Keeping a mesh entirely at the GPU and changing its vertices there with a ComputeShader (Unity5)

texts:
In a Unity game I have an object whose mesh is made of around 10k vertices and I have to make changes to these vertices (position, color, etc) almost every frame.

Considering that such object is always visible to the main camera, I was wondering if there is a way for me to keep the whole mesh in the GPU and do the changes to its vertices there with a Compute Shader.

I know how to use Compute Shaders. What I can't find out is how should I, in Unity, keep a mesh entirely in the GPU. I could use 3 StructuredBuffers, 1 for the vertices, 1 for the vertex-colors and 1 for the UVs of the mesh. However, that is not enough to properly form the mesh in the GPU (it means, with only those I would be displaying just the vertices on scree as in a point-mesh, not exactly the triangles of the mesh).

Is there a way I could achieve such a thing? If so, I would highly appreciate a short example in pseudo-code to point me in the right direction.


texts:
I'm new to Box2D (JavaScript) (and the world of physics/mathematics) so I'm having a hard time working out the methods I need to use to make a spaceship act like it does in the classic arcade game Asteroids. I've tried varying methods and nothing works quite right (as I obviously don't understand what I'm doing).

For example, in Asteroids you can rotate the ship but it turns at a constant rate and won't continue to spin after you let go of the key, unlike the rest of the ship's physics. So I tried SetPositionAndAngle(position, angle-0.1) as an example to make the ship turn without having it rotate after key up, however when I then press the up key to make the ship go forward, it turns left as well as going forwards (via ApplyForce).

Can anybody give some tips on how I should be dealing with Asteroids-type spaceship physics?


texts:
In fighting game, there is an important thing called input buffering. When your character is doing an action, you can input the next action that will activate as soon as possible (the buffer is 5-10 frames).

Has anyone already implemented, or knows the most efficient way to do this?

I thought of things like this:

Enum list moves (a list of all my moves)
if (moves = fireball)
{
    if (Mycharacterisidle)
    {
         Do the fireball
    }
    else if (MycharacterisMoving)
    {
         if (lastspriteisnotfinished)
         {
             InputBuffer++;
         }
         else if(spriteisfinished && InputBuffer < 5)
         {
             Do the fireball
         }
    }
}

Any better ideas?
Thx.


texts: Help me to find a simple 3D game development tutorial in Unreal Engine 4

texts: I am looking already several hours to find a UE4 tutorial that creates a simple 3D game from scratch, but not using Blueprint. Instead I would like to see complete C++ tutorial. Cannot find any resource! Maybe unreal gurus can help on this? A single link of a game from scratch that is being created using C++ with UE4.


texts: Unity - Rotating X on camera changes result of ScreenPointToRay completely

texts:
I am using ScreenPointToRay to draw a Line along my Mouse drag. My code for getting my mouse position looks like so:

public static RaycastHit RaycastScreenPoint(Vector2 mousePosition, LayerMask mask, Camera cam)
{
    var ray = cam.ScreenPointToRay(mousePosition);
    RaycastHit hit;

    if (Physics.Raycast(ray, out hit, float.PositiveInfinity, mask))
    {
        Debug.DrawRay(hit.point, Vector3.up, Color.red, 2);
        return hit;
    }
    else
    {
        throw new System.Exception("Mouse raycast did not hit anything");
    }
}

With my perspective camera at 65, 0, 0, this works great. However, if I change the rotation of my camera to 90, 0, 0, the line is drawn outside the camera view, why is this?

I want this line to be drawn the same no matter the camera rotation.

My code for drawing line:

private void Update()
{
    if (Input.GetMouseButtonDown(1))
    {
        lr.positionCount = 2;
        startPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point;
        lr.SetPosition(0, startPos);
    }

    else if (Input.GetMouseButton(1))
    {
        endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point;
        lr.SetPosition(1, endPos);
    }

    else if (Input.GetMouseButtonUp(1))
    {
        endPos = PointerHandler.RaycastScreenPoint(Input.mousePosition, movementMask, cam).point;
        lr.SetPosition(1, endPos);
    }
}

This image is with the camera rotation at 64, 0, 0. As you can see, the Line is drawn inside the camera view as intended, and follows my mouse:

This image is with the camera rotation at 90, 0, 0. I am dragging my mouse in the middle of the game view, and yet for some reason, the line is ending up outside the camera:


texts: Is there a way to check if a Texture2D has unapplied changes?

texts:
In Unity, we can use the Apply() function of Texture2D to apply any changes that we've made with SetPixel() or SetPixels().
Is there a way to check whether the texture currently has any unapplied changes? I don't see any relevant properties like IsDirty or HasUnappliedChanges, but perhaps there's a less obvious way to check.
My particular use case is that I have a texture which is normally only used for calculations and does not need to be displayed on the screen, so it's normally not necessary to call Apply() after changing the texture. However, I'd like to be able to preview the texture in the Inspector when a particular component is selected, which does require that the texture is Applied. I'm wondering if Texture2D has a built-in way to check for unapplied changes; if not, it won't be difficult to write custom code for tracking this.


texts: Why when loading back the player position and rotation it's loading the player in a different position and rotation?

texts:
State class :

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

[Serializable]
public class SaveState
{
    public float posX;
    public float posY;
    public float posZ;

    public float rotX;
    public float rotY;
    public float rotZ;
    public float rotW;

    public float scaX;
    public float scaY;
    public float scaZ;

    public DateTime LastSaveTime { set; get; }
}

Manager script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System;
using System.IO;

public class SaveManager : MonoBehaviour
{
    public static void Save(SaveState player)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        string path = Application.persistentDataPath + "/player.bin";
        FileStream stream = new FileStream(path, FileMode.Create);

        SaveState data = new SaveState();

        formatter.Serialize(stream, data);
        stream.Close();
    }

    public static SaveState Load()
    {
        string path = Application.persistentDataPath + "/player.bin";
        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Open);

            SaveState data = formatter.Deserialize(stream) as SaveState;
            stream.Close();

            return data;
        }
        else
        {
            Debug.LogError("Save file not found in " + path);
            return null;
        }
    }
}

Test script :

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

public class SaveTest : MonoBehaviour
{
    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.T))
        {
            var player = GameObject.Find("Player");
            SaveState saveState = new SaveState();
            saveState.posX = player.transform.position.x;
            saveState.posY = player.transform.position.y;
            saveState.posZ = player.transform.position.z;

            saveState.rotX = player.transform.rotation.x;
            saveState.rotY = player.transform.rotation.y;
            saveState.rotZ = player.transform.rotation.z;
            saveState.rotW = player.transform.rotation.w;

            saveState.scaX = player.transform.localScale.x;
            saveState.scaY = player.transform.localScale.y;
            saveState.scaZ = player.transform.localScale.z;

            //Save data from PlayerInfo to a file named players
            SaveManager.Save(saveState);
        }

        if(Input.GetKeyDown(KeyCode.L))
        {
            //Display loaded Data
            var player = GameObject.Find("Player");
            player.transform.position = new Vector3(SaveManager.Load().posX, SaveManager.Load().posY, SaveManager.Load().posZ);
            player.transform.rotation = new Quaternion(SaveManager.Load().rotX, SaveManager.Load().rotY, SaveManager.Load().rotZ, SaveManager.Load().rotW);
            player.transform.localScale = new Vector3(SaveManager.Load().scaX, SaveManager.Load().scaY, SaveManager.Load().scaZ);
        }
    }
}

I can see the created saved file player.bin 1 KB size.

This is a screenshot when I press the T button to save :
On the left bottom game window. And the inspector player info position and rotation when saving.

I press the T button once to save while the player is in coroutine.
When the game start the player is not moving but rotating using coroutine. Not sure if the coroutine if saving while the player is rotating make the problem.

This is a screenshot when pressing the L button and the inspector of the player position and rotation :

Not same position and rotation when loading.


texts: What is Surface.set_colorkey() in Pygame?

texts: In pygame, what does Surface.set_colorkey() do? Explain it in a very easy way please. Also, what exactly does it do? I heard it makes parts that are the same color as the colorkey transparent, but what is the point of that?


texts: Problem with Update(GameTime) Methods and Pause implementation

texts:
I have the pause function implemented and it works correctly in that it dims the player screen and stops updating the gameplay.

The problem is that GameTime continues to increase while it is paused, so my method that checks gameTime versus previousSpawnTime before spawning another enemy gets messed up and if the game is paused too long it is noticeable that the next enemy draws far too early.

Here is my code for the enemy update.

private void UpdateEnemies(GameTime gameTime)
    {
        // Spawn a new enemy every 1.5 seconds
        if (gameTime.TotalGameTime - previousSpawnTime > enemySpawnTime)
        {
            previousSpawnTime = gameTime.TotalGameTime;

            // Add an Enemy
            AddEnemy();
        }
...

I also have other methods that depend on gameTime.  I've tried getting the total pause time and subtracting that from the total game time, but I can't seem to get it to work correctly if that is the way I should go about solving this.

If you need to see any other code let me know.  Thank you.


texts: Missing z-axis rotation for transforming between two vectors

texts:
I'm trying to rotate a cube so that it's facing up, but am getting hung up on the final implementation details. It now reliably will rotate the x,y axis to the correct side, but the z-axis is never rotating (See photos of before and after rotation). When I'm using the code below I always get '0' for my rotationVector.z. What am I missing here?

// Define lookAt vector
lookAtVector = GLKVector3Make(0,0,1);

// Define axes vectors
axes[0] = GLKVector3Make(0,0,1);
axes[1] = GLKVector3Make(-1,0,0);
axes[2] = GLKVector3Make(0,1,0);
axes[3] = GLKVector3Make(1,0,0);
axes[4] = GLKVector3Make(0,-1,0);
axes[5] = GLKVector3Make(0,0,-1);

CGFloat highest_dot = -1.0;
GLKVector3 closest_axis;

for(int i = 0; i < 6; i++) {
    // multiply cube's axes by existing matrix
    GLKVector3 axis = GLKMatrix4MultiplyVector3(matrix, axes[i]);
    CGFloat dot = GLKVector3DotProduct(axis, lookAtVector);
    if(dot > highest_dot) {
        closest_axis = axis;
        highest_dot = dot;
    }
}

GLKVector3 rotationVector = GLKVector3CrossProduct(closest_axis, lookAtVector);

// Get angle between vectors
CGFloat angle = atan2(GLKVector3Length(rotationVector), GLKVector3DotProduct(closest_axis, lookAtVector));

// normalize the rotation vector
rotationVector = GLKVector3Normalize(rotationVector);

// Create transform
CATransform3D rotationTransform = CATransform3DMakeRotation(angle,  rotationVector.x, rotationVector.y, rotationVector.z);

// add rotation transform to existing transformation
baseTransform = CATransform3DConcat(baseTransform, rotationTransform);
return baseTransform;

Before 3d Rotation

After 3d Rotation

Implementation based on this post


texts: Break a learning barrier with Java + LWJGL

texts: I have been coding with Java and LWJGL for some time. I mainly use thebennybox's tutorials, but I can't always remember the 3D rendering. But even when I have a 3D rendering models, planes, cubes, etc. I can't get past that. I need a good LWJGL tutorial! I look up to Notch and I know a good bit about Minecraft's history, and wish I could code as fluently as him. I also understand a good bit of Java.


texts: Why do not Easy Mobile Pro scripts know about each other?

texts:
I am getting this error when I try to build the project:

Assets\EasyMobile\Scripts\Modules\NativeAPIs\NativeUI\Nati
veUI_AlertPopup.cs(68,17): error CS0103: The name 'AndroidNativeAlert' does not exist in the current context

I tried adding this to my NativeUI_AlertPopup.cs:

    #if UNITY_ANDROID
        using EasyMobile.Internal.StoreReview.Android;
    #endif

Hint says unnecessary using.
Googling, searching Unity EMP forum and thread did not bring any results.
Unity version 2019.2 .net 4.x EMP 2.5
If I try adding a breakpoint it says:

The breakpoint will not currently be hit. Unable to find a corresponding location.

AndroidNativeAlert is a static class, have have no clue why it can't been seen from the other one.


texts:
I'm implementing a turn based game where players can meet other players in matches via Apple Game Center. Each match has two players.

I want to make a global ranking of all players using Apple Game Center. This ranking serves two purposes:

each player will know his/hers ranking.
a player can be matched to another player with a similar skill.

My current thinking is something like this:

A win gives +1 points
A lose gives -1 points
An aborted match, or not accepting a match gives -1 points.
0 is the minimum score.
The leaderboard will present the score of each player.
Players will be placed in groups according to their score. Each group can cover a range of scores, and players will be matched with players from the same group.

I have the following questions:

Do you like my suggested scoring solution?
Is it possible to accomplish an effective match making with this approach? I mean, some groups can have very few participants. Maybe only one. Of cause you can try to do a match making with a lower group, but that can also be empty, and it will take time. How shall I solve this?
I've not released the game, and I don't know how many players it will have. Is it possible to make the grouping dynamic in some way? More players requires more groups.
Is it possible to make players that does not accept matches to lose points? I only want to have active players in top of the ladder.

So far I've only found this input:
https://stackoverflow.com/questions/9355799/can-i-make-a-ladder-systemlike-battle-net-with-using-just-game-center


texts:
I'm trying to create a game in HTML canvas, but somehow it keeps flickering, I've taken a look at the tutorial and I perceived that my code is more or less similar. Can anybody help me fix this?

var canvas = document.getElementById("screen");
var ctx = canvas.getContext("2d");
var pwidth = 16;
var pheight = 16;
var cwidth = 12;
var cheight = 12;
var mariox = 16;
var marioy = 120;
var tiles;
var marioSprite;

function drawMarioSprite(){
    marioSprite = new Image();
    marioSprite.src = 'file:///C:/Users/User/Desktop/img/characters.gif';
    marioSprite.addEventListener('load', e => {
    ctx.drawImage(marioSprite, 276, 44, pwidth, pheight, mariox, marioy, cwidth, cheight);
    //pic x and y, pic width and height, canvas x and y, canvas width and height
    });
}//drawMarioSprite() end

//draw floor
function draw() {
    tiles = new Image();
    tiles.src = 'file:///C:/Users/User/Desktop/img/tiles.png';
    tiles.addEventListener('load', e => {
        drawTiles();
    });
}
function drawTiles(){
    for (let x = 0; x < 25; x++){
        for (let y = 11; y < 13; y++){
                ctx.drawImage(tiles, 0, 32, pwidth, pheight, x*12, y*12, cwidth, cheight);
        }
    }
}//drawTiles() end

function clear(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function component(){
    drawMarioSprite();
    draw();
}
function level1(){
    console.log('level1');
    clear();
    component();
}

var inter = setInterval(level1, 1000);


texts:
I am currently developing an indie game using XNA/C#. I would like to give players the opportunity to try a free (but somewhat limited) demo version of the game. Nevertheless, the player should be able to purchase the full version of the game from within the demo version (after short download) immediately unlocking the full version.

The tricky part is that I would like to permanently remember this purchase as I would like to give players how purchased the game the opportunity to download additional content etc. for free later. Nevertheless, the user should be able to switch computers or reinstall the game without loosing that "purchased"-flag. One (maybe) possible way would be to give each user a serial number that can be checked once at gamestart. Is there a library etc. to support this or is there maybe another best-practice for these kinds of things.

I guess the well-known payment processors as BMC-Micro and Fastspring do not support this, do they.

PS: I would like to keep the game DRM-free.


texts: XNA 4.0: Problem with loading XML content files

texts:
I'm new to XNA so hopefully my question isn't too silly. I'm trying to load content data from XML.

My XML file is placed in my Content project (the new XNA 4 thing), called "Event1.xml":

<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
  <Asset Type="MyNamespace.Event">  // error on this line
    <name>1</name>
  </Asset>
</XnaContent>

My "Event" class is placed in my main project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace MyNamespace
{
    public class Event
    {
        public string name;
    }
}

The XML file is being called by my main game class inside the LoadContent() method:

Event temp = Content.Load<Event>("Event1");

And this is the error I'm getting:

There was an error while deserializing intermediate XML. Cannot find type "MyNamespace.Event"

I think the problem is because at the time the XML is being evaluated, the Event class has not been established because one file is in my main project while the other is in my Content project (being a XNA 4.0 project and such).

I have also tried changing the build action of the xml file from compile to content; however the program would then not be able to find the file and would give this other warning:

Project item 'Event1.xml' was not built with the XNA Framework Content Pipeline. Set its Build Action property to Compile to build it.

Any suggestions are appreciated. Thanks.


texts:
I need a way to draw resolution independent text in my game. That is, I need to be able to zoom in on text and never see pixel artifacts.

Can anyone make any suggestions on how I could go about it?


texts: In what kind of variable type is the player position stored on a MMORPG such as WoW?

texts:
I even heard J. Carmack quickly talk about it...

How a software can track a player's position so accurately, being on a such huge world, without loading between zones, and on a multiplayer scale ? How is the data formatted when it passes through the netcode ?

I can understand how vertices are stored into the graphic card's memory, but when it comes to synchronize the multiplayer, I can't imagine what is best.


texts:
I have gone through a few posts that talks about changing the GraphicsDevice.BlendState and GraphicsDevice.DepthStencilState (SpriteBatch & Render states). . however even after changing the states .. i cant see my 3D model on the screen.. I see the model for a second before i draw my video in the background. .  If i dont play my video then i can see the 3D model ..Here is the code:

GraphicsDevice.Clear(Color.AliceBlue);
spriteBatch.Begin();

if (player.State != MediaState.Stopped)
{
    videoTexture = player.GetTexture();
}

Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

// Draw the video, if we have a texture to draw.
if (videoTexture != null)
{
    spriteBatch.Draw(videoTexture, screen, Color.White);

    if (Selected_underwater == true)
    {
        spriteBatch.DrawString(font, "MaxX , MaxY" + maxWidth + "," + maxHeight, new Vector2(400, 10), Color.Red);
        spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);
        spriteBatch.Draw(butterfly, handPosition, Color.White);

        foreach (AnimatedSprite a in aSprites)
        {
            a.Draw(spriteBatch);
        }
    }

    if(Selected_planet == true)
    {
        spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);
        spriteBatch.Draw(butterfly, handPosition, Color.White);
        spriteBatch.Draw(videoTexture,screen,Color.White);

        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

        foreach (_3DModel m in Solar)
        {
            m.DrawModel();
        }
    }
    spriteBatch.End();


texts: Three button combination to open next scene

texts:
I have thirty (30) buttons in a trivia game, they are laid out in the following configuration with three rows:

( A, B, C, D, E, F, G, H, I, J)
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
(00,01,02,03,04,05,06,07,08,09)

Using these combinations of buttons and clicking one and only one from each row I have a thousand (1000) - three (3) button combinations. E.g.: A27 would be one combination of the thousand possibilities. These are not random combinations each opens a very specific scene.

What I am trying to do is create a C# script that when I click any of these three (3) button combinations it will open a new scene. Once that scene is open I’m okay because then have my own scripts attached to the single buttons in the new scene to continue to a further scene.

What I can’t figure out is the syntax, should I use if Statements such as -  if (Btn_A)  &&  (Btn_1)  &&  (Btn_01) then load scene such and such? Then do I attach the script to the canvas then to each of the three button combinations (A 1000 Scripts combinations)?


texts: Spine, Dragonbones or Live2D for interactive 2D animation?

texts:
I'm planning to make a game with some interactive 2D animation. For example, when the player holds mouse button, the character gradually pulls his bow, and releases it when the player releases mouse button. I think skeletal animation works better than frame-by-frame sprites for this purpose, right?
I googled for a while and it seems there are several tools can do that, like Spine, Dragonbones and Live2D. But I have no idea what's the difference and which one I should choose. Could you share your advice/experience on it? Also do they have API for Unity?
I'm have a bit programming experience with Unity, but I know nothing about 2D animation, so please bear with me if this question makes no sense.


texts: Why is GameObject.FindGameObjectsWithTag returning null?

texts:
I'm currently working on refactoring my gravity simulator, but I'm running into a problem. I have two GameObjects, both tagged with the tag "Body", as you can see below:

I'm attempting to cache a list of all GameObjects like so:

private GameObject[] _bodies;

...

public void Start()
{
    ...
    this._bodies = GameObject.FindGameObjectsWithTag("Body");
    ...
}

When I try to use the value this._bodies though, as seen in the foreach loop below, I get a NullReferenceException.

foreach(GameObject body in this._bodies)
{
    ...
}

I have verified that the value of this._bodies is null, using this piece of code:

Debug.Log(this._bodies);

I'm honestly stumped as to why GameObject.FindGameObjectsWithTag is returning null when I run it. Is there a way to solve this?

For reference, here's the full code involved:

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

[RequireComponent(typeof(Rigidbody))]
public class GravityComponent : MonoBehaviour
{
    public double gravitationalConstant = 6.674 * Mathf.Pow(10, -11);
    public Vector3 startingForce;

    private GameObject[] _bodies;
    private Dictionary<GameObject, double> _massProducts;
    private Rigidbody _bodyRigidbody;

    /// <summary>
    /// Initalize various private values and caches, like the
    /// cache of bodies, masses, etc.
    /// </summary>
    public void Start()
    {
        this._bodyRigidbody.AddForce(this.startingForce);
        this._bodyRigidbody = GetComponent<Rigidbody>();
        this._bodies = GameObject.FindGameObjectsWithTag("Body");
        this._massProducts = this._bodies.ToDictionary(
            body => body,
            body =>
                  this.gravitationalConstant
                * this._bodyRigidbody.mass
                * body.GetComponent<Rigidbody>().mass
        );
    }

    /// <summary>
    /// Calculate the attractions between two separate bodies, and
    /// then apply the calculated attraction.
    /// </summary>
    public void ApplyAttraction()
    {
        foreach(GameObject body in this._bodies)
        {
            Vector3 bodyPositionDifference = body.transform.position - this.transform.position;
            double attraction = this._massProducts[body] / bodyPositionDifference.sqrMagnitude;
            this._bodyRigidbody.AddForce(bodyPositionDifference * (float)attraction);
        }
    }

    public void FixedUpdate()
    {
        Debug.Log(this._bodies);
        this.ApplyAttraction();
    }
}


texts: How can you put all images from a game to 1 file?

texts:
I've just finished a basic RPG game written in C++ SFML, I've put a lot of effort into the game and I'd want to distribute it, however I've ran into a small issue.

Problem is, I have well over 200 images and map files (they're .txt files which hold map codes) all in the same folder as the executable, when I look in the folder, it makes me want to cry a little bit seeing so many resources, I've never seen a game which shows you all the resources directly, instead I believe they pack the resources in a certain file.

Well, that's what I'm trying to achieve: I'm hoping to pack all the images in 1 file (Maybe the .txt files as well) then being able to read from that file or easily add to it.


texts:
I'm developing a game for Android using LibGDX in Android Studio.
I recently found out that some sounds in my game fail to play. I noticed that every time a sound fails to play, these are the logs:

04-12 10:49:51.784 24234-24283/com.gadarts.parashoot.android E/AudioTrack: AudioFlinger could not create track, status: -12
04-12 10:49:51.785 24234-24283/com.gadarts.parashoot.android E/SoundPool: Error creating AudioTrack
04-12 10:49:52.503 24234-24283/com.gadarts.parashoot.android W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client; transfer 4, track 44100 Hz, output 48000 Hz

This is the code I use to play the sounds:

public long playSound(SFX fileName, boolean loop, float volume, boolean randomPitch) {
        if (GameSettings.SOUND_TOGGLE) {
            try {
                Sound sound = prepareSound(fileName);
                if (randomPitch && GameSettings.SOUND_RANDOM_PITCH) {
                    return setRandomPitch(loop, sound, volume);
                }
                if (loop) {
                    return sound.loop(volume);
                } else {
                    return sound.play(volume);
                }
            } catch (GdxRuntimeException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }
private Sound prepareSound(SFX soundFile) throws GdxRuntimeException {
        try {
            String soundPath = SFX.fileAttribute.SFX_FOLDER_NAME.getValue() + "/" + SFX.fileAttribute.SOUNDS_FOLDER_NAME.getValue() + "/" + soundFile.getParentDir().getValue() + "/" + soundFile.getValue() + "." + soundFile.getFormat().getValue();
            Sound sound;
            if (!sounds.containsKey(soundFile.getValue())) {
                sound = Main.getAssetsManager().get(soundPath, Sound.class);
                sounds.put(soundFile.getValue(), sound);
            } else {
                sound = sounds.get(soundFile.getValue());
            }
            if (sound == null) {
                throw new GdxRuntimeException("preparing sound failed - sound not found.");
            }
            return sound;
        } catch (GdxRuntimeException e) {
            throw e;
        }
    }

The sound files are in WAV format.
Any ideas how to fix it? Thanks in advance!

Update: I've found out that this problem appears only on my Nexus 5X. I tried it on Xiaomi Redmi Note 4X and it didn't happen.


texts:
So, I can happily render an infinite square grid by moving said grid whenever the camera moves out of a grid square,

auto diff = (cameraTranslation - gridTranslation);
bool moveGrid = false;

if (diff.x > cellSize.x / 2)
{
    gridTranslation.x += cellSize.x;
    moveGrid = true;
}
else if (diff.x < -cellSize.x / 2)
{
    gridTranslation.x -= cellSize.x;
    moveGrid = true;
}

if (diff.z > cellSize.z / 2)
{
    gridTranslation.z += cellSize.z;
    moveGrid = true;
}
else if (diff.z < -cellSize.z / 2)
{
    gridTranslation.z -= cellSize.z;
    moveGrid = true;
}

if (moveGrid)
    gridTransform.Translate(gridTranslation);

However, when working with a hexagonal grid, things get a bit more complicated. (For that matter, if the grid was textured, I'd have to adjust the grid translation based on the tessellation distance... ouch.)

In this case, I'm dealing with a wireframe hex grid:

And I'm a little unsure how to treadmill in this case.

The first thing that comes to mind is that, given that the camera starts in the center of a hexagon, determine if the camera has exited the cell in which it started. If so, adjust grid position by

float angle_from_center = atan2(camera.z-grid.z,camera.x-grid.x);
grid.x += cell_size.x * cos(angle_from_center);
grid.z += cell_size.z * sin(angle_from_center);

Which will probably work, but the issue gets more complicated when considering that I'm not only checking if the camera has moved a certain distance from the cell center, but if it has crossed a border.

I could clamp the angle of the camera relative to the cell origin to 1/12 of a circle, which would make hex boundary calculation easier, but this seems like a hack.

Any suggestions? I'm 75% sure I'm over thinking this one.


texts: How to make object move in exact gametime in Monogame, XNA?

texts:
I have recently started learning monogame. The big question i faced is how to make object move, when gametime variable has an exact value.

//Update method in Game.cs
     float delta = (float)gameTime.ElapsedGameTime.Milliseconds / 1000f;
        if (CurrentState != null)
            CurrentState.update(delta);

     if (Keyboard.GetState().IsKeyDown(Keys.Enter))
            SetState(new GameState());

    //GameState.cs, there is a box that's need to be moved in 5 seconds
    Vector2 boxpos = new Vector2(800, Game1.graphics.PreferredBackBufferHeight / 2 - 100);
    float olddelta = 0;
    public void update(float delta)
    {
        float newdelta = delta;
        if (newdelta - olddelta >= 5)
        {
            boxpos += new Vector2(0, -200);
            olddelta = newdelta;
        }
    }

I've drawn a box in my gamestate's draw method using spritebatch.Draw(Box, boxpos, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f);, but it's position remains constant.
I really have no idea how to do it in a right way. Hope can receive some help.


texts: Object Movement / Constant Movement Rate or Vectors

texts:
I' have some code to move a unit between two points in a series of points, when it reaches the next point it pops that point off the front of a stack, and then heads towards the next in the stack.

Issue:
When the movement between two points occur, the object will slow down towards the point, I want a constant rate of movement between the two points, I'm thinking of implementing something like a physics engine would, there is some groundwork there already, however it would not ideally work with this code the way I think I should do it, I'd have to rewrite a fair deal where you create a movement vector in the direction of the point?

void EntityUnit::unitgmovement(CWaypoint* &TargetVec, float updatetime, CWaypoint* &Sourcewaypoint)
{
    // BUG why use this twice ? what happening ? probably resolve later tonight.
    // a moveto function without path smoothing used for infantry and tank movement
    pf_Dest = TargetVec;
    pf_Source = Sourcewaypoint;
    double xDistance = pf_Dest->GetX() - unit_x;
    double yDistance = pf_Dest->GetY() - unit_y;
    double zDistance = pf_Dest->GetZ() - unit_z;
    double distance = sqrt(xDistance * xDistance + yDistance * yDistance + zDistance * zDistance);
    util_timer_movedelay += updatetime;
    if (util_timer_movedelay > speed / 1000)
    {

    //  cout << "Distance:" << distance << endl;
        if (distance > 0.05)
        {
            unit_x += (0.5 * xDistance * speed * updatetime);
            unit_y += (0.5 * yDistance * speed * updatetime);
            unit_z += (0.5 * zDistance * speed * updatetime);
            util_timer_movedelay = 0;

        }
        else
        {
            pf_Source = pf_Dest;
            dest_reached = true;
            pf_waypoints.pop_front();

        }
    }

}

If I have an objects X,Y,Z global location, how do I create a movement vector for them ? that would work with this so I have a constant rate of movement? Or is there another easier work around ?


texts:
Let's say, theoretically, that I'm developing a first person shooter with, of course, a map with things like walls. In the client code, the player is obviously halted upon collision with these wall objects. The server, however, only receives the player's location coordinates.

Without some sort of data encoding in the client, the player could easily read the network communication to the server and send false coordinates to the server, allowing them to go wherever they wanted.

My question is, is there a way to encode  this location message to the server before it exits the client binary such that it would be extremely difficult for  someone to read? Even by someone who disassembles the code to try and break the encoding? Or do all player collisions have to be detected by the server?


texts: What do I need to get an independent developer license for CryENGINE 3?

texts:
I have searched Google and CryEngine forums and I can't seem to get a solid answer to this question.

I have seen threads where developers are complaining that they can't sell their game because they can't get a licence after finishing their project.

Now, I am considering using CryEngine for my game because I like the royalty system, as it means I do not have to make any upfront payments but I don't want to have to get through the game and then find that I Crytek refuse to give me a license because I didn't know what the rules were, or something.


texts: Disable free look camera movement when touch detected on mobile joystick

texts:
I'm using free joystick pack form asset store and in scene have two cameras (first person and third person). Switching cameras with toggle.
Game starts with first person camera. Moving with fixed joystick and rotating camera with swiping on right side of screen. Everything is ok for this step.
For third person camera I'm using cinemachine free look camera. Cinemachine camera is reacting to joystick touch inputs. I need to disable camera movement when interacting with joystick. Tested on Android device
Cinemachine settings:

Third Person movement script:
void Update()
{
        if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
        {
            x = joystick.Horizontal;
            z = joystick.Vertical;
        }
        else
        {
            x = Input.GetAxis("Horizontal");
            z = Input.GetAxis("Vertical");
        }

        Vector3 direction = new Vector3(x, 0, z).normalized;

        if (direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + camTps.transform.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            characterController.Move(moveDirection.normalized * speedTps * Time.deltaTime);
        }
 }

Any ideas and suggestions is appreciated


texts:
This project "Locomotion Skills for Simulated Quadrupeds" creates an animation for the dog model in the program. However if you go into the project's files the dog's skeleton is made of individual obj files for each bone. How were the bones loaded into the program to make the complete animation? It's as if the position of the obj's were attached to... the vector I guess? Can anyone elaborate a little more?

My reasoning for this is because I want to replicate it, create a model (to be animated) out of separate model files. I guess my question is how make one character out of several separate model files? Thanks


texts:
I need to make realistic human movement (3D) using mouse click.

Get mouse click point using Raycast.
Smoothly Slerp to LookRotation.
Move transform.forward.

Everything works fine, except I have problem with circular movement (close radius).

Example If dont move transform.forward while Slerp to LookRotation or MoveTowards instead of transform.forward it will be spinning like whirligig on circular movement.
Example If do move transform.forward while while Slerp to LookRotation it will distort trajectory of straight direct movement.

Is there any solution to move circular realistic (not spin like whirligig) and move straight direct when needed (not distort trajectory)?

I need straight movement from first example and circular movement from second.

        if (Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            RaycastHit[] hits = Physics.RaycastAll(ray);

            foreach (RaycastHit hit in hits)
            {
                if (hit.transform.tag == "Ground")
                {
                    DestinationPosition = new Vector3(hit.point.x, transform.position.y, hit.point.z);

                    DestinationRotation = Quaternion.LookRotation(DestinationPosition - transform.position);

                    break;
                }
            }
        }

        if (Vector3.Distance(transform.position, DestinationPosition) > 1)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, DestinationRotation, RotationSpeed * Time.deltaTime);

            transform.position += transform.forward * MovementSpeed * Time.deltaTime;

            //transform.position = Vector3.MoveTowards(transform.position, DestinationPosition, MovementSpeed * Time.deltaTime);

            animation.CrossFade("run");
        }
        else
        {
            animation.CrossFade("idle");
        }


texts:
I am trying to shadowmap a large terrain, I position my light that it is always at the position of the player and looking at the player, the problem is that the shadows now move with the player, I tried to set the position to 0 1000 500 and look at the player always and its a good improvement however the player moves out of the light there are now no shadows :(

How am I supposed to make the light so it covers the entire terrain and everything has shadows all the time without the shadow moving effect?

I am really stuck right now, do I need to somehow calculate scene bounds? would that help at all?


texts: Key events outside of an SDL application

texts:
I'm developing an app under C++ and SDL running in Ubuntu. I'm using the SDL events to handle the keypad buttons. My problem is that my app launch other programs and it should close they with a key combination, but I can't detect the user presing buttons outside of my app.

¿How could I do this?


texts:
I'm made a model for a project at work (depicted in the image bellow) that requires me to create a somewhat realistic movement on a curled phone wire.

Here is what i have tried so far:
I've tried setting up a joint chain in Maya and skinning the mesh to the joints. I then un-parented all of the joints so that none of them are part of the same hierarchy. Then i imported the mesh into Unity, and added a character joint component to each of the joints. I then recreated the hierarchy from Maya by using the "connected body" function within the character joint components of each of the joints. Lastly I made colliders for each of the joints.

This procedure works as intended when I try to recreate the desired effect on a separate chain of individual spheres where each sphere gets its own joint, but on the wire everything is freaking out and the mesh practically explodes.
This leads me to believe that the problem is caused because the mesh is being skinned to multiple different joints that aren't part of the same hierarchy before specifying the hierarchy within unity.

Is there a way to use a regular joint hierarchy from Maya as to avoid avoid setting it up in Unity? Is it easier to maybe use cloth simulation? Is there another work around that I should try?

I mostly work within Maya so my work within unity is usually limited to model import, setup and assignment of materials and setting up animation controllers. This means that my Unity knowledge is pretty basic, and as such it'd appreciate it if the responses could be spelled out so that a newbie like me can understand it :)

Thanks so much in advance.


texts:
So I have a school assignment where we have to make a little program that makes random abstract art out of drawn rectangles.

This is what is should look like:

It's the top right element of the canvas.

Now the function has to consist of this: When you press 'backspace' the program should generate a new abstract 'painting' within the boarders and it should consist of 15 new random sized and random colored rectangles.

We work in a custom game engine that our teacher made for us. It uses C# as base.

I basically got everything to work. When I press backspace 15 random rectangles are being drawn on the canvas with random colors. The only problem is that when I press backspace again, only the colors change but not the rectangles.

Here is a pastebin link to the code I made so far: http://pastebin.com/YCrjb2T1

So basically for the colors I made a list (CreateRandomColorList) of int arrays. The int arrays are being  filled with 3 random numbers between 0 and 255 (RGB colors). These 3 numbers can be given as parameters to set the color. So everytime you press backspace the rectangles are given new random colors.

I wanted to do exactly the same for the rectangles themselves but that did not seem to work.

There are 3 parameters you can give to a rectangle: The x position on the canvas, the y position on the canvas, the width and the height.

Any insights/tips on what could be wrong would be welcome, I hope my explanation is good enough.


texts:
I have a large list of points (millions) in 2d. Let's say it's a star map. Each star has a radius and position in space.

I want to render this map at different level of details. From a single star to entire star system, galaxy or even universe. I also want it to be fast.

So I started with a quad tree approach: loaded every point into the tree. At any moment of time I can query a tree with a simple question: Give me top N points in this region

But what is a top? I thought to myself that quads can be compared based on total radius of points that they host. So, this gives me sorting order to work with, and the algorithm boils down to a mix of quad tree and a priority queue:

priorityQueue.push(rootQuad)

while priorityQueue.size < N {
  let node = priorityQueue.pop() // take the largest node
  for each child of node {
    if child.intersects(region) {
       priorityQueue.push(child)
    }
  }
}

After this algorithm is done, I can render each point either at its location (if it's a leaf), or at the node's center of mass (if it's intermediate node). It works very fast, and gives decent results.

However there is a problem with this approach. Let's consider a simple grid of points:

If I render each intermediate quad tree node at node's center of mass, then I get these artifacts, where two nodes are collapsed into one:

It almost feels like I should start from leaves, combine individual points into single cluster, until I get N clusters, but this would kill performance.

What would you recommend to do to avoid such artifacts?


texts: Placing an AABB close to a point so that it doesn't intersect any other AABBs

texts:
Give a 2D space with a bunch of non-intersecting AABBs, and a point in this space (that may or may not be inside an AABB), how can I find the closest place where I can place a new AABB of a given size?

For example, given the space below and the point 'X', the correct position for a certain AABB is marked in green:

One solution I have considered is to iterate every edge, and find the closest point on that edge where the shape doesn't intersect (if such a point exists). This could be achieved by placing the AABB at the closest point on the given edge, and then if it's intersecting with another shape, move it to the outside edge of that shape, along the given edge, repeating until it's no longer intersecting. This seems relatively expensive (though could probably be optimized by using some kind of spatial hashing), but might be the way to go.

I'm wondering if there are any obvious or not so obvious solutions I'm missing here.


texts:
Reading up on ECS, I've tried to implement a simple 'game', if you can call it that.
Basic concepts :

You have planets(entity), they produce gold. (gold is a component inside planet)
Planets can build buildings on themselves(Buildings component)
A building(entity) has associated gold costs(Costs component)

But costs component has Gold in it(or it needs to anyway)

As to my question :
Am I close with my interpretation of ECS(Should components be inside other components?)
Are resources a valid Component? if not, where would it make sense to place them?

Edit for clarity :

ECS - Entity-Component-System.
My entities are empty hash tables of components.
My components are used inside systems for game logic, the Treasury entity has a Gold component and the IncomeSystem updates that component.

Other components (Buildable, Population, Moveable)


texts:
I´m having a rough time trying to figure out a proper way of dealing with key mapping and key bindings in unity.
The built-in unity input manager is useless to me since it doesnt support key mapping ingame and you cant acces it via script, you can only change your key bindings on the game laucher, but not ingame.

I guess I will need to create my custom InputManager to replace the unity one but im pretty much lost in this matter.
So far I´m beein doing some research and now I know how to create a basic but robust input manager in C++ (thanks mainly to this tutorial http://www.gamedev.net/blog/355/entry-2250186-designing-a-robust-input-handling-system-for-games ) But as i said I dont know how to translate this into unity c#.. My first idea was to create a complete new input manager from scratch that use an xml file to store the key binding data,  but I dont know if you think this is the wrong way to follow. First of all I dont even know how could I acces RawInput in unity. Checking the script documentation was of no use in this matter, i found something about keyboard events but they only work under OnGUI function and I dont know if i should use it then...

I know there are some commercial plugin out there for that solve this purpose but thats not the point, I´m trying to do it this by myselft

Could someone explain to me how could I make my own InputManager from scratch or give me some indication to put me in the right way to this?

I apologize for my bad english btw

-EDIT FOR CLARIFICATION:

Im trying to achieve just the typical key mapping menu but I must be able to access this menu ingame, i mean, via pause menu. ingame->pause menu-> options-> controls.  for example, I have the jump action mapped to the space bar, In my controls menu I select remap this this action. A dialog propt and wait for me to press the new key to map to the jump action. I press ctrl (or whatever key)...and then I update the dictionary, jump action = ctrl (or whatever keycode it is). But the issue is, how do I know which key did I just pressed while the dialog waiting for a new key was active? Should I use something like:

void OnGUI() {
    Event e = Event.current;
    if (e.isKey && remapping)
        remap(action, e.keycode);

or if not just a bunch of if statements, one for each keycode of the keyboard i mean

if Input.getKey('keycode')
    remap(action, keycode);

what surely will work but just use about 100 if statemens

I hope I explained myself clearly now. Anyway I was doing some research before start writting any code but I will do a script what I thought so far and then post it for a better understanding.


texts: How to separate my rendering from game loop?

texts: If I have a (complex) operation that takes a long time for it to finish, for instance, a couple of seconds, my frame rate drops far below the acceptable. How could I still implement it while it is not messing up my frame rate?


texts: Varibles Initialized in Awake are null in other script's Start

texts:
I have a component gameState Attached to one gameobject called GameState:

public class gameState : MonoBehaviour
    {
        public Context stateMachine;
        private void Awake()
        {
            PlayerGameobject p = GameObject.Find("Player").GetComponent<PlayerGameobject>();
            stateMachine = new Context(new Playing(), p);
        }

On another gameObject I have this component:

public class PlayerGameobject : MonoBehaviour
{
    void Start()
    {

        gameState = GameObject.Find("GameState").GetComponent<gameState>();
    }

}

When I try to use gameState within PlayerGameobject's Update method I find that stateMachine is null.

 if (gameState.stateMachine.CurrentState == "Playing"){}
      //       ^^^^ null

why is statemachine null? I initialized it in awake which should run before start. gameState is not null and other public variables assigned in Editor are not null.


texts:
I'm trying to implement GPU-based geometry clipmapping and have problems to apply a simple heightmap to my terrain. For the heightmap I use a simple texture with the surface format "single". I've taken the texture from Catalinz's XNA blog.

What I'm trying to do is just getting the single float value from the texture at the vertex world coordinate and apply the value to the Y-Value of the Vertex. I'm applying the heightmap through the shader, because there is no fixed grid in-code it could be applied on. What I've tried so far was using the tex2Dlod function, but there seems to be no output or an output of 0. The Direct X vertex shader's code looks like this:

float4 worldPos = mul(float4(pos.x,0.0f,pos.y, 1.0f), worldMatrix);
float elevation = tex2Dlod(HeightmapSampler, float4(worldPos.x, worldPos.z,0,0));
worldPos.y = elevation * 128;

Where HeightmapSampler is a point-mirror sampler of the heightmap texture. Here is the output, I actually get no elevation:

And here's the heightmap I'm using:


texts: Use of solid brushes and CSG in level building

texts:
Since Quake 1 (I think it was the first), level design tools for FPS games have used solid brushes and CSG operations to define level geometry instead of more conventional poly modeling tools you see in general purpose 3d applications like 3DS MAX.

Why is this? Is it:

More productive for the level designer?
More likely to lead to closed geometry that won't screw up potentially visible set pre-calc?
Results in lower poly count (more cumbersome tools dissuade designers from adding too much detail)?
...


texts: Re-sizing the form without scaling the GUI

texts:
I am writing a turn based strategy game in C#.  My GUI implementation consists of class that extends Form containing a class that extends Panel.  When I render the GUI I draw to the paint method in the panel.

I am trying to figure out what is the best way for handling form re-size events.  I know I want a minimum window size, but I would prefer to not have a maximum or a set size.

Ideally the GUI would reveal more/less of the map as the user changes the window size.  I would like to avoid scaling the graphics if at all possible.

What is the best way to handle re-size events?


texts: Unity3d simple material color display correctly in windows built but yellow color turns to blue in android build?

texts: I have a simple roll a ball game as shown in unity 3d tutorials, and I have set the wall color as a shade of yellow using the standard shader and material. This runs flawlessly in windows application, however when running in android phone( Nexus 5 MM) the wall turns into a blue color. Can anyone tell me how to fix it?


texts: How to address players struggling with simple controls?

texts:
I have an HTML game I built with Phaser 3, and I can't decide what to do with the controls. I've changed them several times, and now I feel like I've hit a sweet spot between usability and fun. However, I still see people struggle.

The game involves a boy with a slingshot that can be pulled back and fired to knock the enemy's head off. There are two virtual buttons on both side of the screen that are tapped to turn the character. I'm considering having the character turn automatically, so that the slingshot is the only mechanic involved and the game can be picked up and played without instructions. However, I feel like this will destroy the whole point of being fast to turn and shoot the enemy.

Should a simple game like mine require instructions, or is usability more important?


texts: How to client/server game using Google App Engine (Looking for tutorial.)

texts:
(NOTE: This is a duplicate of a question I asked on SO, having temporarily forgotten about GameDev <hang head in shame>.  When one is answered, I will link it back to the other.)

I'm trying to do my first client/server game using Google Apps Engine as my back end (specification requirement.) I've done the tutorials (Java), but that all seems highly browser-centric.

Basically, I'd like my (mobile, not that it matters) app to:

Allow the user to create a game-account (NOT their Google account!)
Log-in with that account.
Press the "MARCO" button to send an account-identified request to the server.
Get a "POLO" response from the server.

As data (like a JSON object, XML-DOM or similar), not as a web-page.

Can anyone point me to a good tutorial/sample project/detailed reading to help me achieve that? I'm pretty sure that, once I get that working, I can do all the rest of it -- but I'm having the "stuck at the starting gate" problem, not being able to work up basic account-login, and non-HTML data exchange.

Thanks!


texts:
I want to create a full screen Triangle/Quad so I can blur the box that is the quad I made. I want to do this in the vertex buffer. I tried this code:

    struct VSQuadOut {
    float4 position : SV_POSITION;
    float2 uv: TEXCOORD;
};

// outputs a full screen triangle with screen-space coordinates
// input: three empty vertices
VSQuadOut VSQuad( uint vertexID : SV_VertexID ){
    VSQuadOut result;
    result.uv = float2((vertexID << 1) & 2, vertexID & 2);
    result.position = float4(result.uv * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f);
    return result;
}

I want something like this

Any ideas?


texts: Turn based game in HTML/JS/CSS - new joiner messes with state of game while animations are still running for other players

texts:
I developed a playing cards web app using HTML/JS/CSS.
Communication with the server is performed using WebSocket.
The server is developed in Java Spring.

The game proposes to join one of the many available tables where you can immediately perform an action.

The players who are already in the table are perfectly in sync with each other, as when they receive a message from the server, I show a screen overlay preventing them from clicking on any element on the table while an animation is running.
After the animation is terminated, the game becomes available and runs normally.

My problem is that if a new player joins the table after a message has been sent by the server, then he can perform an action while the animation is still running for the other players, thus starting a new animation for them at the same time and the game becomes messy.

Is there a way to either prevent the new joiner from performing an action before the animation has ended for the rest of the players ? Do you have any other idea how I can solve this issue ?

Thanks for your help


texts:
im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this.

i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0.

this is my code.

    public class PlayerScript : MonoBehaviour {
public float speed = 150f;
float hInput ;
void FixedUpdate()
{
    Move (hInput);

}

public void Move(float horizontalInput){
    if (horizontalInput.Equals(1)) {
                    rigidbody2D.AddForce (Vector2.right);

    }if (horizontalInput.Equals(2)) {
        rigidbody2D.AddForce (-Vector2.right);
    }if(horizontalInput.Equals(3)) {
        rigidbody2D.AddForce (Vector2.up);
    }
    if(horizontalInput.Equals(4)) {
        rigidbody2D.AddForce (-Vector2.up);
    }
    }

    public void StartMoving(float horizontalInput){
    hInput = horizontalInput;
    }
    }


texts: Algorithm for smoothing a network object's movement

texts:
We are building multiplayer game where there's no central server managing the game.

Each player is responsible for sending out its state to all connected players.

In addition, all clients run prediction between received packets, to keep all objects moving in between state packets.

We also smooth out the positiobs received from remote clients, for example in scenarios where the received oosition is small enough and should be moved smoothly from the current predicted position.

The issue I am trying to handle is how should the algorithm behave in case it hasn't finished smoothing out the position yet, and a new state is being received?

The smoothing algorithm currently operates for a given configured duration (e.g: 80 ms). Should a new incoming state cancel the ongoing smoothing? What is done in such cases?

One option is to never reset started smoothing, that is, run for the whole 80  ms, but update the target position in case new state is received.

Another option would be to reset (start the 80 ms count all over again. This time with the new start/end positions).

Both options have their issues. I am wondering whether there's a formal way to deal with this.


texts: Apparent tunneling with issue bounding box collision detection

texts:
I'm working on a Break Out game remake and I'm getting a weird bounding box collision detection behavior.

It seems like the ball is going under the paddle even if the hit is on top. Weird enough the ball doesn't go through the paddle but instead crawls within its height and then it bounces off.

My collision detection code is as follows:

bool collision =
            std::abs( m_x - actor.m_x ) * 2 < ( m_texture->Width() + actor.m_texture->Width() ) &&
                std::abs( m_y - actor.m_y ) * 2 < ( m_texture->Height() + actor.m_texture->Height() );

This is the collision behavior I'm getting for some hits:


texts: What is the best design pattern to apply effects and abilities?

texts:
What would be the best design pattern to apply effects and abilities in a game. For example:

I have a unit that has base stats like attack power, defense etc. The unit can hold several items that will boost one or more of these effects. Also the unit can have several skills that can either boost stats, or be like a special attack.
The trick behind the skills is, it should get stronger per level.

I have the following requirements:

Data for the skills and items should be loaded through (for example) xml or serialized classes.
The skills should contain a level system. Each level they increase in strength (but not with a fixed percentage each level).
An item or skill can have multiple effects (time based and immediate effects).
The skills should have something like an Execute method with a target unit (for example special attack on unit Y) This effect has a graphical representation (like a rocket firing) that should occur and an effect (damage, armor decrease etc) on the target. This effect could be applied over time or instantaneously.

What is the most usefull design pattern to achieve this?

I can think of the following:

I have several classes: Unit, Ability, Effect.

The Unit class has an array of applied Effects. On add to and on remove from this array the Apply and Remove methods on the Effect class are called, with the Unit object as parameter. The Effect class then handles the appropriate Boost or Decrease on the Units properties.
This will work, however, I don't see this working with time based effects.

Are there better solutions?


texts:
Starting with Unity having had experience of XNA im not sure if the way i want to solve my problem is the correct way. So id like the opinion of more experienced people.

I am doing a 2.5D game and have no need for 3D sounds that generate from a certain 3D position. I am used to creating a sound manager class that handles the loading of sound assets and has a static public method for each sound effect. This way it works like a toolbox i can call SfxManager.PlayDeathScreamSfx(); from anywhere in the solution.

How could i do the same in Unity?

I have tried making a game object called soundmanager and given it static methods that would play the sound effects but the SoundClips needs to be static for the static methods to be able to use them. And if the SoundClips are static then they dont show up in the inspector and i cant drag'n'drop a sound file on them to reference them.

What to do?


texts: OpenGL 3.0+ framebuffer to texture/images

texts:
I need a way to capture what is rendered on screen, i have read about glReadPixels but it looks really slow.

Can you suggest a more efficient or just an alternative way for just copying what is rendered by OpenGL 3.0+ to the local RAM and in general to output this in a image or in a data stream?

How i can achieve the same goal with OpenGL ES 2.0 ?

EDIT:

i just forgot: with this OpenGL functions how i can be sure that

I'm actually reading a complete frame, meaning that there is no overlapping between 2 frames or any nasty side effect
I'm actually reading the frame that comes right next to the previous one so i do not lose frames


texts: My GLSL shader isn't compiling even though it should. What should I investigate?

texts:
I'm porting an iOS game to Android. One of the shaders I'm using wouldn't compile until I reduced the number of uniform variables. Here are the uniform definitions:

uniform highp   mat4 ViewProjMatrix;
uniform mediump vec3 LightDirWorld;
uniform mediump int  BoneCount;
uniform highp   mat4 BoneMatrixArray[8];
uniform highp   mat3 BoneMatrixArrayIT[8];
uniform mediump int  LightCount;
uniform mediump vec3 LightPos[4]; // This used to be 12, but now 4, next lines also
uniform lowp    vec3 LightColour[4];
uniform mediump vec3 LightInnerOuterFalloff[4];

My issue is that the GLSL shader wouldn't compile until I reduced the count of the above arrays from 12 to 4. My understanding is that if those 3 lines were arrays of 12 then I would be using 56 vertex uniform vectors. I query the system at startup (GL_MAX_VERTEX_UNIFORM_VECTORS) and it says that 128 are available. Why wouldn't it compile with 56? I'm having issues on the Kindle Fire.


texts: Add XNA math references to non-xna project

texts:
I'm developing some game with server/client structure, and the client will predict the movements, but it should be validated by the server.
In the client part, I got it moving nice, but now I'm trying to test it with the server calculating the movement. The problem is the client I use the xna classes like Quaternion, Vector3, Matrix, etc. Is there anyway to get this XNA classes in the server without making it a xna project??

I found a site with sources of the classes like XNA geomtries, but when I tried it out, it dont got the same results, so I'm still looking for the sources of it, or someother sources that gets at the same results for me to add into the server


texts:
I'm trying to move an object to the coordinates 48.7, 51.07, 102.8, but it does not move. I did some test to make sure that "OnMouseDown" works, and it does, I think it could not be finding the object "upgradeone".

public class click1 : MonoBehaviour {
    GameObject Upgradeone;
    GameObject cube;

    // Use this for initialization
    void Start () {
        Upgradeone = GameObject.Find("upgradeone");
        cube = GameObject.Find ("Cube");
    }

    void OnMouseDown(){
        Upgradeone.transform.localScale = new Vector3(48.7f,51.07f,102.8f);
    }
}


texts: Why are parts of this Unity scrollrect not being bound to the mask?

texts:
I'm setting up a system for people to load up extra levels.  Since I don't know how many levels are going to be loaded I have a UI prefab that gets added to the main Level Load UI. However, the Text components of the prefab are not being bound by the scrollrect mask.  The panel, images and button all are, and they are all children of the panel getting added to the panel that is the scrollrect's content.

Another related problem, each of the prefabs also has a button on it.  I've given it some alpha because I find that once it's in the scrollrect only the top half is clickable.  You can see below that it only highlights (as red) if your on the top half of the button.  The exception is that the final button will work if your mouse is anywhere on the button.  This isn't an issue for the buttons if they're just placed in the scene.  It only happens inside the scrollrect.

I have a smaller version of the project right here for download.  The 'main' gameobject starts a script that instantiates the main 'Load Level Screen' prefab and populates it with the 'LoadLevel - Single' prefabs.

I've been banging my head against the wall for over a week now, so any help would be appreciated!


texts:
Im Currently develop a little Dungeon Crawler. The Singeplayer works fine, but it also should have multiplayer so i implemented it. But there's one problem. I have no idea how to make the AI chase the player and the other players. In singleplayer it works like this :

if(distanceToPlayer <= 400f){

   entity.chase(playerEntity);

}

Heres my full chasing code :

// in enemy update method i put all multiplayers into a map with their login number..

 // Pick a random Multiplayer and chase him

        boolean isAvaible = false;

 //Convert Map to Object array
        Object[] values = ((EnemyEntity)arg0).mpSortedPos.values().toArray();

        int rdm = 0;

        float randomValue = 0;

        // wenn map isnt empty
        if(((EnemyEntity)arg0).mpSortedPos.size() > 0){

            rdm = generator.nextInt(values.length);

            randomValue = (float)values[rdm];

            isAvaible = true;

        }

        //selecting the key
        // +2 because the first joined player is the second Player in the game so it begins with connection 2, the second with 3 and so on.
        int key = rdm + 2;

        // Only printing stuff
        System.out.println("Found a Map : "+((EnemyEntity)arg0).mpSortedPos + "Size of da HashMap : "+ ((EnemyEntity)arg0).mpSortedPos.size());
        System.out.println("Found a Random Value : "+rdm + " "+randomValue );
        System.out.println("Found a Key: "+key + " "+((EnemyEntity)arg0).mpSortedPos.get(key) );

        // When the multiplayer is near the enemy than
        if (/*((EnemyEntity)arg0).distanceToNextPlayer < 400 && arg0.isAlive() == true */ isAvaible && ((EnemyEntity)arg0).mpSortedPos.get(rdm) != null && ((EnemyEntity)arg0).mpSortedPos.get(rdm) < 400) {

            ((EnemyEntity)arg0).activated = true;

            arg0.stateMachine.changeState(CHASE_ENTITY);

        }

This is my code for multiplayer chasing but it doesnt work ... any ideas ? What could i improve ?

But how should i do that with multiple players ? Any ideas ? :)


texts: How to create character avatars without lots of artwork?

texts:
I am writing a mafia RPG game where it is required to hire "goons" to be part of your family, I have about 10 "goon" avatars/artwork (+ retina) already and am hitting a problem.

The problem is that for every avatar I imply a character (with stats), so if I have,

avatar001.png = {Character: Bob Health: 100 Skills: ... }
avatar002.png = {Character: Mike Health: 100 Skills: ... }
avatar003.png = {Character: Alan Health: 100 Skills: ... }

The implication is that these 10 pieces of artwork I have are 10 specific characters, with specific names and stats.

This causes me a problem in that in order to get a good selection of goons, I'm going to need a lot more than 10 avatars; probably even in the hundreds if not thousands.

Bottom line, To do this, it's going to be expensive.

The way Tiny Tower did it was to have a template and use this, and I've thought of a similar solution -- a faceset generation tool, but I'm mot sure if its going to work; all the current goon avatars I have are custom designed and would not lend themselves to 1-4 generic face templates.

The only solution I have right now is to,

  Just use the 10 avatars I have and randomly generate the name, stats,
  class levels or whatever  -- and don't worry about it.

But I don't know if this is good enough and I'm looking for alternative solutions -- how would you create character avatars without spending loads on literally thousands of avatars?

Thanks.


texts:
I am a 6th grade student and I would like to be a video game designer.  In class, we all had to choose a career that we would like to have and interview someone with that career.  Finding a game designer locally has been difficult, so I thought I would try online.  If some of you would take the time to answer these questions I would be grateful.  Some of the questions I have for you are:

Why did you choose your career?

What kind of education did you have to complete for this career?

How is math related in this career?

What would a day in your normal life in this career typically look like?

How do you dress for this career?

What is your favorite part about this career?

What kind of games do you create?

You do not have to answer all of the questions but it would be much appreciated if you would answer most of them.  Thanks!


texts: Libgdx Sprite rotation around specific point

texts:
I made complex dynamic body that rotates around other body that is static. It works perfectly, however I got messed up with sprite position on that body.
Here's what I have now

and here's what I need to have

I will add my code

private Body createSide(float x, float y, Sprite tmpSprite, boolean sharp){
      BodyDef bDef = new BodyDef();
      bDef.type = BodyDef.BodyType.DynamicBody;

    PolygonShape shape = new PolygonShape();
    if(!sharp){
        shape.setAsBox(1.8f / PPM, 0.2f / PPM);
    } else {
        shape.setAsBox(0.2f / PPM, 1.8f / PPM);
    }

    FixtureDef fdef = new FixtureDef();
    fdef.shape = shape;

    bDef.position.set(x, y);
    Body body = world.createBody(bDef).createFixture(fdef).getBody();
    body.setAngularVelocity(-1f);
    tmpSprite.setPosition(bDef.position.x * 32, bDef.position.y * 32);
    return body;
}

private void createBody(int y, final int V_WIDTH){
        staticBody = createStaticBody(y, V_WIDTH);
        Body rightSide = createSide(5.5f, 15, sprites[0], true);
        Body leftSide = createSide(9.5f, 15, sprites[1], true);
        Body top = createSide(7.5f, 17, sprites[2], false);
        Body bottom = createSide(7.5f, 13, sprites[3], false);

        bodies[0] = rightSide;
        bodies[1] = leftSide;
        bodies[2] = top;
        bodies[3] = bottom;

...
...
...
    }

and here's my draw method

@Override
    public void draw(SpriteBatch sb) {
        for (int i=0; i<bodies.length; i++){
            sprites[i].setRotation(bodies[i].getAngle() * MathUtils.radiansToDegrees);
            sprites[i].draw(sb);
        }
    }


texts: add random walls with an array in 3D xna 4

texts:
I'm trying to add walls to my 3D game. I created a wall entity and added model array

public Walls()
{
  modelArray = new Model[10];
}

public void Initialize(ContentManager contentManager)
{
  for (int i = 0; i < modelArray.Length; i++)
  {
    rnd = new Random();
    sidesWall = rnd.Next(-4, 4);
    forwardWall = rnd.Next(-8, 0);
    modelArray[i] = contentManager.Load<Model>("wall");
  }
}

Draw method:

public void Draw(Camera camera)
{
  foreach (Model m in modelArray)
  {
    foreach (ModelMesh mesh in m.Meshes)
    {
      foreach (BasicEffect effect in mesh.Effects)
      {
        effect.EnableDefaultLighting();
        effect.PreferPerPixelLighting = true;
        effect.World = GetWorldMatrix();
        effect.View = camera.ViewMatrix;
        effect.Projection = camera.ProjectionMatrix;
      }

      mesh.Draw();
    }
  }
}

It doesn't work and it shows only one wall.

How can I make it work?


texts: Why don't my generated instances update when I change their prefab?

texts:
I’m making an Editor tool -- a ScriptableWizard -- that instantiates a prefab on a grid. But I find that when I update the prefab, the instances don’t update.

When I instantiate prefabs interactively in the Editor by dragging them from the Project panel to the Scene or Hierarchy, then updates to the prefab affect the instances as expected.

I see another difference between my scripted instances and the ones created when I drag the prefab into the scene: when I do it interactively, the instance in the hierarchy is listed in blue. But the instances I create from script using the same prefab are listed in black, similar to objects created directly in the scene.

Here’s the hierarchy; the “JitterPrefab” was dragged into the scene, and the ones under “gridParent” were instances of the JitterPrefab generated from my script:

Here’s how I’m generating the instances:

public GameObject prefab; ...

void OnWizardCreate() { ...
  Transform instance = Instantiate (prefab.transform, pos, rot, parent.transform);
  instance.name = string.Format ("L{0:D2}-R{1:D2}-C{2:D2}", l, r, c);
  ...
}

When I make a change on the prefab, e.g. change the radius of the Jitter script from 0.025 to 0.25, the manually created instance updates:

But the script-generated instances do not:

What am I doing wrong? Why are my scripted instances no longer connected to the original prefab?
And, separately, how to I tell in the editor (or in script) whether an object in the scene is an instance of a prefab or not?


texts: Are there technical reasons to use short variable names in shader code?

texts:
I have been reading and writing both GLSL and CG for the past few years, and have noticed a trend. In programming, we are generally advised to be as meaningful and concise as possible with variable names, but I see this suggestion being ignored almost every time I look at shaders.

Here is a random example I grabbed off of Shadertoy:

vec3 tex_wmcs(vec2 p)
{
    float s=mix(0.2,1.2,sqrt(smoothNoise2(p*3.0)));
    vec3 col=mix(vec3(0.15,0.2,0.2)*0.4,vec3(0.2,0.15,0.11)*0.7*s,sqrt(max(0.0,sm...
    vec2 p2=p*vec2(4.0,10.0)+vec2(smoothNoise2(p*24.0),smoothNoise2...
    p2.x+=floor(p2.y)*0.5;
    float bh=pow(0.5+0.5*cos(floor(p2.y)*14.0)*cos(floor(p2.x)*1.0),2.0);
    float brick=brickt(p2);
    vec3 bn=normalize(vec3(brickt(p2+vec2(1e-3,0.0))-brick,b...
    ...
}

Is there a practical reason so many graphics programmers minify their code to such a point?

Is there a technical downside to spelling out brickNormal instead of leaving it as bn, or using brick_tangent or brickTexture instead of brickt?