texts: Updating bots/AI behavior after a fixed elapsed timestamp in game loop?

texts:
I am developing a HTML5 game in javascript. Now I have created a few bots and they should be able to change their orientation after a few seconds/a fixed timestamp in the game loop.

Suppose my game loop is like this:

function loop() {
    bots.updateOrientation();
    bots.render();
    player.update();
    player.render();
    requestAnimationFrame(loop);
}

How can I make that happen in my game loop?


texts:
I am looking for an algorithm that moves an object at a regular speed in a snake-circular like movement. This movement should look pseudo-random and smooth, later on I am going to add other body parts, but so far this is the essential.

My try so far has consisted in having a random value t that chages each frame:

t= Random.Range(t-20f,t+20f);

and according to it I was employing a direction. The result should be more directions that are smoothly different, so that the movement itself is smooth.

I would score the solution with 7/10, and moreover, it doesn't describe like short circles, but rather larger ones and the negative result is that the object exits the scene quite fast.

What is your algorithm solution? On the internet I found solutions where the player moves the head of the snake, but here the object acts like an autonomous object.


texts:
Today I got issue with a script we solved here. OK, Here if enemy enter player ring, he "enemy" gets inside player list. Now, if group of enemies get inside this the ring I need to sort them by distance from player. The first one in the list will be the closest enemy from player, and so on. If one die, new enemy will add to list that nearest/closest to player. Will my GameObject list allow me to do this ? or I need to make new Vector3 list ? I'm using System.Linq.

    public List<GameObject> enemiesInRange = new List<GameObject>();
    public int hox;

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

    hox = enemiesInRange.Count;
    if (hox == 3)
        print("Frist enemy near you is " + enemiesInRange[0] + ", " + enemiesInRange[1] + ", " + enemiesInRange[2]);
    //   enemiesInRange[0].GetComponent<enemypath>().enemey_checker = true;
    //   enemiesInRange[1].GetComponent<enemypath>().enemey_checker = true;
    //   enemiesInRange[2].GetComponent<enemypath>().enemey_checker = true;

}

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("enemy") && hox < 3)
        enemiesInRange.Add(other.attachedRigidbody.gameObject);
}

void OnTriggerExit(Collider other)
{
    if (other.CompareTag("enemy"))
        enemiesInRange.Remove(other.attachedRigidbody.gameObject);
}

I really hope to solve this issue and finish from this point.


texts: How do I prevent getting an access denied loading a file in XNA, when I have the application running in the program files directory (in Windows 7)?

texts:
I'm creating an app in XNA.

I'm trying to load a custom save file. I named the file with my own custom extension. It's an XML file serialized with the DataContractSerializer.

I've tried several things to load the file. And they all work when I'm running in my development environment, or when the game is running from most folders, but if the game has been placed in the program files folder (or any other protected by Windows 7), the game won't load my custom files, but it will load images and other items that the content importer handles naturally.

Things I have tried:

Directly loading the file using the DirectoryInfo.CurrentDirectory() then scanning for files, and loading them.
Using the StorageContainer.TitleLocation
Creating a custom importer, and loading them into the content pipeline

In all cases, it works fine running in my IDE (C# Express 2008), but when the app is running from Program Files, I get the following error:

Access to the path 'C:\Program Files\MyFolder\MyAppName\Content\CustomFolder\Blah.CustomExtension' is denied.

I am running as administrator (though obviously, I eventually don't want the end user to need this right).

Any suggestions?


texts: Using coroutines to instantiate larger GameObjects in Unity/C#

texts:
We are making a scroller type game for mobile platforms and we got pretty far (Beta is already out). Now we are adding some additional content and are starting to experience a noticable lag when starting the game. I know about coroutines, but never actually used them, so I was wandering if it's possible to use them to instantiate larger GameObjects (or groups of objects). This is the code we use at the moment to create bullets (this is just an example, I have more similar methods):

Func<string, Pool.Poolable> bulletCreator = x => { return Instantiate(Resources.Load<Pool.Poolable>(x)) as Pool.Poolable; };

and then we use this method to create a certain amount of bullets:

Bullets = new Pool(4, () => { return bulletCreator("Bullet"); });

This creates 4 bullets (it fits our game desing, the player is restricted to 4 bullets and can refill them with powerups). There are different types of bullets that we create with the same function, and we create them at the start, pool them, and then use them when they are needed.

Now this is one of the "heavier" methods, and I'm trying to find a way to speed it up. I tried something like this:

  IEnumerator CreateBullets()
  {
     Func<string, Pool.Poolable> bulletCreator = x => { return Instantiate(Resources.Load<Pool.Poolable>(x)) as Pool.Poolable; };
     Bullets = new Pool(4, () => { return bulletCreator("Bullet"); });
     yield return Bullets;
}

Bullets is a global private variable of type Pool. The problem we are having is that when we try to shoot, Unity trhows the Object not set to an instance error.
Is what I'm trying possible, or is it like in the regular C# that no crossthread calls are allowed. If it's not possible, what are our options? I know we could probably make a short animation and run that in the coroutine while the main thread instantiates everything. Any advice is very welcome.

Thanks in advance.


texts: How do you set up PhysFS for use in a game?

texts:
After my recent question on GD I've been advised to use PhysFS to pack all my game data in 1 file. So I have, and the decission wasn't light, because I've tried out every library in my answers but none contained a single good tutorial whatsoever, in fact PhysFS is the poorest documented library I've ever seen.

After attempting to set up PhysFS in my game I realized it's not as simple as adding the headers to the project, it appears something much more complicated, in fact after my first attempt to install PhysFS the compiler ran out of memory to display errors, it reached the critical count of 50 errors.

So basically what I'm asking here is: How can I set up PhysFS on my game? I'm using Code::Blocks IDE on Windows XP SP3;


texts: Is there an explanation of whats going on from the software down to the hardware that explains tearing? One would think that the graphics card would just tell the LCD display to change whenever it wants to. Why do LCD displays have refresh rates at all?


texts: Performance of manipulating a mesh in realtime

texts:
Does Unity allow streaming mesh data that can be continuously changed?

I have a level that is dynamically changing based on some parameters. The number of triangles stays the same, they just change positions.

I'm speaking of around 2000 triangles that need their position updated each frame (they follow a spline that is computed on CPU), running on mobile phones.

I can't use a TrailRenderer because the object is a whole level. I can't use bones, because I need to know the final position for each vertex for my custom collision code.

The mesh should be marked Mesh.MarkDynamic.


texts: When do I save the buffer data to the database?

texts:
My entire game is server side and I use nodejs with mysql.

When players connect or join a game, their player data (Items, Stash, Quests, etc) all get stored into the memory buffer.

For example, if a player joins a game and there are 40 items on the floor and he decides to pick them all up, it's easier just to add that to their Inventory object instead of using a insert statement each time. Then, when that user disconnects I can save all that data respectively. (Now that I think of it, that query would run 40 insertion rows..)

That's the problem I have though, do I save the data during the looting process or wait until the player disconnects and run a db update to save their memory buffer (only the changed buffer) to the database?

The Issue I have with that is, if a player picks up over 40 items in the game, that's going to be a lot of sql insertions when they disconnect..

Imagine them finding a ton of items from mobs and having a huge amount of new updated buffer data that needs to be stored.. (after they disconnect), that would be a dreadful update. Especially if they stored hundreds of items in their stash or whatnot. Hmmm.


texts:
I have a code that I've been messing around with and the monster attack (monster.ma)
isn't randomising after the first time it's called upon (elif statement). I've tried to make it a tuple since they are immutable but it doesn't randomise after the first time. I was told to make a class and that's what I have done but it still doesnt work right. My attack variable (att) works right, but monsters' attack gets stuck. I know I can code the monster's attack into the elif statement, but I want to be able to just call upon it when needed.

import random

class monster():
    hp=50
    ma=random.randint(5, 20)
    xp=random.randint(15, 30)
a=1
exp=0
while a==1:
    if monster.hp<=0:
        exp+=monster.xp
        print"you have killed the monster"
        print("you get, "+str(monster.xp)+" exp from monster"
              "you now have, "+str(exp)+" exp")
        break
    elif monster.hp>=0:
        print"swing your sword"
        att=random.randint(5, 15)
        monster.hp-=att
        print"you do, "+str(att)+" damage to monster"
        print"monster does, "+str(monster.ma)+" damage to you" #<----------------here


texts: Problem with SDL_Mixer/MikMod playing XM files properly

texts:
Some of the music I've made for my game have note bends in them (1xx Portamento up)...The problem is that when they play in my game, the note bends and then goes right back to original note instead of staying at the new tone it bends into.

I believe this to be an issue with SDL_Mixer and not with the XM file itself since it plays just fine in any tracker program I load it into.  Is there anything in the SDL_Mixer loading/playing functions that I could do to fix this?


texts: Integrating accelerometer data samples to get velocity and displacement

texts:
I am working on an android app built in Unity that would allow the users to track their movements by just using the data coming from the device sensors. I have read about similar issues already and I am aware that this approach doesn't really give any good results in practice, due to the inaccuracy of the sensors, but I still need to measure the performance of this method for research purposes.
My implementation makes use of the Unity function InvokeRepeating to fetch the acceleration values at a certain rate and to then calculate the velocity and displacement by using a two step integration:
private readonly float dt = 0.001f;
private void Start()
{
    //...
    Input.gyro.enabled = true;
    Input.gyro.updateInterval = 0.001f;
    InvokeRepeating("AccelerationSample", 0.0f, dt);
}

private void AccelerationSample()
{
    Vector3 data = Input.gyro.userAcceleration * 9.81f; //Fetch the current acceleration
    lastAccel = data * kFilteringFactor + lastAccel * (1.0f - kFilteringFactor); //Apply Kalman filter
    totalAccel += data - lastAccel; //Accumulate the acceleration value

    vel = initVel + (totalAccel * dt); //Calculate the current velocity
    initVel = vel; //Update the initial velocity for the next frames

    distance += vel * dt; //Calculate the distance from the velocity value
}

The raw acceleration values are multiplied by 9.81f to match the real world acceleration (since the values coming from the gyroscope are normalized) and are filtered through a Kalman filter to reduce noise. The acceleration values are accumulated in order to take into consideration both the positive and negative parts of acceleration that the gyroscope provides when the device moves. The velocity and displacement values are then calculated using simple physics formulae.
This approach gives decent results when considering acceleration and velocity only. Though the displacement value does not seem to be updating as fast as I expected, and sometimes the calculations go completely off. Also, when the acceleration goes back to zero after any movement, the evaluated velocity does not go down to zero as well, therefore I need to find some conditions under which I can safely reset its value.
I hope I was able to properly describe the issue and that some of you might help me to revise my implementation and/or give me any hints on how I should go about the problem.


texts:
Okay so this is really odd I have a game object (a rock) that even though is really high detail drops my fps from around 70 steady to 12!
Now the object is divided into LOD's and the closer I get to the object the worse it gets!
I have created a Material for each LOD of the object where i replace the normal map with a lower LOD (The other channels stay the same).
The import settings for the different LODS looks like this:

Now as of the textures they are set to 2k (all of them)
Can anyone tell me why this is happening?
The object itself looks like this inside the game:

Even my scene view has framerate issues when looking at it.


texts: How to trigger OnMouseX events on Kinematic Rigidbody2D object with a different collider than one used for collisions?

texts:
I have a use-case where I have an object with a Collider2D and a Kinematic RigidBody2D in order to do Kinematic movement.
However, I also want to be able to select/hover that object with a OnMouseDown/OnMouseEnter/etc, using a larger collider than I would use for the kinematic movement.
My current attempt at a solution is to have Physics-related scripts/rigidbody2d/collider2d as the top level game object, and to have a child object, with a larger collider2D which will respond to OnMouseX events.

In order to ignore OnMouseX events on the parent, I'm putting it into its own user_ignore_raycasts layer (I need it as its own layer for the layer collision matrix). I'm also putting the child in its own user_use_raycasts layer.
I'm passing that into a script that sets MainCamera's event mask:

using UnityEngine;

[RequireComponent(typeof(Camera))]
public class CameraEventMasker : MonoBehaviour
{
    [SerializeField]
    private LayerMask cameraEventMask;

    // Start is called before the first frame update
    void Awake()
    {
        GetComponent<Camera>().eventMask = cameraEventMask;
    }
}

What I notice is that OnMouseX events on the child will work IF the RigidBody2D on the parent is deleted...however, if the RigidBody2D is there, I won't receive any events. Anyone know why this is the case, and if there are other workarounds or solutions?


texts: Non-random enemy movement implementation

texts: I would like to implement enemy movement on a X-Y grid. Would it be a good idea to have a predefined table with an initial X-Y position and a predefined "surveillance path"? Each enemy will follow its path until it detects a player, at this point it will start chasing the player using a chasing algorithm. According to a friend of mine this implementation is good because the design of a good path will provide to the user a sort of reality sensation.


texts: What is the intended usage of the Sprite class in LibGDX

texts:
I am making a small game in LibGDX and it all works, sprites are moving etc. The drawing is mainly done in the render() method of a Screen, using Batch.draw(TextureRegion). So far so good.

But now I would like my sprites to rotate. There are Batch draw methods for rotation (I think), but I noticed a bunch of useful methods in tne Sprite class. Problem is I do not know how to use them without making the rest of the program ugly.

I could have a Sprite as a member of each "game object", but that makes direct dependency of the game model on drawing mechanism, specifically LibGDX. Besides I can see problems with serialization and duplicate parameters (Sprite x,y vs model x,y etc) and unnecessary overhead.

Or I could subclass Sprite, which would probably be orders of magnitude messier.

Is there a common way of clearly separating the model part and rendering part of  a small game? And how is Sprite typically used?


texts: Orthographic Viewport whose bounds are equal to screen Window bounds?

texts:
Ive been rattling my head trying to figure out how to do this. I am not working on a 3D application so I did not expect to need to understand transforms, projections, or viewports.

Essentially what I want to do is to setup my viewport, view, & projection so that whenever I call GraphicsDevice.DrawPrimatives() the values of the VertexPosition's position can be pixel values. For example, If I wanted to draw a rectangle that bordered the screen I would do:

VertexPositionColor[] vertices = new VertexPositionColor[5];
vertices[0] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);
vertices[1] = new VertexPositionColor(new Vector3(1920, 1080, 0), Color.Red);
vertices[2] = new VertexPositionColor(new Vector3(1920, 0, 0), Color.Red);
vertices[3] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);
vertices[4] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);

As of right now, if i do:

VertexPositionColor[] vertices = new VertexPositionColor[5];
vertices[0] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Red);
vertices[1] = new VertexPositionColor(new Vector3(1, 1, 0), Color.Red);
vertices[2] = new VertexPositionColor(new Vector3(1, -1, 0), Color.Red);
vertices[3] = new VertexPositionColor(new Vector3(-1, -1, 0), Color.Red);
vertices[4] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Red);

I get:

How do I set it up so that my VertexPosition coordinates are 1:1 with pixels?


texts: How can I make a gameobject snap to something when it gets close to it?

texts: Any idea if there is a way I can make a gameobject snap to something when it gets close to it? Like drag a cube around and when it gets close to something then snap to it.


texts: Why is my XInput gamepad press stamp not working?

texts:
I'm trying to add basic gamepad input to my c++ DirectX game but i'm having some trouble creating a press stamp (registers the press only the first time it's pressed if button held down).

The entire input class is here:
https://gist.github.com/anonymous/28be899570c72fe7ae98

My ButtonPressed function:

bool Input::wasGamePadButtonPressed(int padNum, WORD button)
{
    if((gamepad[padNum].wButtons & button) &
        ((gamepad[padNum].wButtons & button) != (prevGamepadState[padNum].wButtons & button)))
    {
        return true;
    }
    return false;
}

The It's just as basic press stamp, if the button is down, and the button was not down before, return true, else return false.

In my input::strobe() i strobe all the inputs and collect their states. at the beginning of the strobe i copy the current states and save them to a previous states structure

void Input::strobe(void)
{
    //hold on to the previous states for input stamping
    memcpy(prevKeys, keys, sizeof(keys));
    memcpy(prevGamepadState, gamepad, sizeof(gamepad));

    //gather keyboard
    HRESULT err;
    err = keyboard->GetDeviceState(sizeof(keys), (LPVOID) &keys);
    if((err == DIERR_INPUTLOST )|| (err == DIERR_NOTACQUIRED))
    {
        keyboard->Acquire();
    }

    //gather mouse
    err = mouse->GetDeviceState(sizeof(mouse_state), (LPVOID) &mouse_state);
    if((err == DIERR_INPUTLOST )|| (err == DIERR_NOTACQUIRED))
    {
        mouse->Acquire();
    }

    //strobe controllers
    if(hasGamepads)
    {
        for(int ii = 0; ii < 4; ii++)
        {
            ZeroMemory(&gamepad[ii], sizeof(XINPUT_STATE));
            XINPUT_STATE state;
            DWORD result = XInputGetState(ii, &state);

            if(result == 0)
            {
                gamepad[ii] = state.Gamepad;
            }
        }
    }
}

This works fine for my keyboard press stamp, which is very similar to the gamepad press function, but the game pad one refuses to work for some reason, firing true every frame for as long as i hold down the button.

It seems really straight forward so i cannot think of why it't not working. the only thing i can think is an issue in the strober, which i did not write originally (most of the basic directinput stuff was given in a class i took), or its me misunderstanding bitwise masks and I've got that gamepadpressed function totally wrong.


texts: What is the fastest way to work out 2D bounding box intersection?

texts: Assume that each Box object has the properties x, y, width, height and have their origin at their center, and that neither the objects nor the bounding boxes rotate.


texts: Colour values of a pixel array from a spritesheet image wrong (C++, SDL2)

texts:
So basically what i want to do is create a 2D tile based rendering system in C++ that renders each pixel on the screen manually.
Rendering an individual pixel on the screen works just fine (or render the whole screen blue for example).
But i want to load the individual pixel colours of my sprites out of a spritesheet image and heres my problem:

I am able to create the image and access the pixels of the image, however the individual pixel values seem to be wrong. (I compared the pixel values with the supposed hexadecimals on paint.net)

Heres my code for the spritesheet:

    SpriteSheet::SpriteSheet(std::string path, int tileWidth, int tileHeight)
    :
    path(path),
    tileWidth(tileWidth),
    tileHeight(tileHeight)
{
    image = IMG_Load(path.c_str());

    if (image != NULL){
        width = image->w;
        height = image->h;
        pixels = (Uint32 *) image->pixels;
        std::cout <<std::hex <<  pixels[17] << std::dec << std::endl;

        //this prints out: 3030303 when it should be FF007F46

    }
    else{
        std::cout << "SpriteSheet couldnt be loaded!" << std::endl;
    }
}

Note that the pixel format is: AARRGGBB

Edit: I tried using a ".jpg" instead of a ".png" and i got different colour values again, but still not the right ones.

Edit2: I'm pretty sure the pixel format in which my image is getting loaded in is wrong.
Any ideas how to get it to ARGB8888? I tried using SDL_ConvertSurface and SDL_ConvertSurfaceFormatbut i can't seem to get it right.


texts: Determine if the player should be able to interact with a door

texts:
You know the drill, standard first person door mechanics. How do they do it?

My most noticeable and frustrating problem is when there is a door within range and in view, but the closest door is actually behind the player.

I'm aware of the "dot product trick" but say the player position is point 1, what is point 2? The center of the doors bounding box? The center of the open door way?

Any insight would be gold.


texts: What AI algorithm to use to find hidden shapes in a Battleships-like game

texts:
I'm developing a game similar to Battleships, only using different shapes. A single type of shape will be used within a game session, by both the human player and AI. There will be several objects spread out on the map (10x10 grid).

I want to find a way to guess the location and position of the human player's "ships" after I have one or more hits.

I'm aware that there will be a lot of randomness involved, but I want the AI to be smart enough to pose a challenge to the human player.

I'm thinking about having the AI "sweep" the map and evaluate each possible shape, somehow assign a probability to a certain position and maybe refine the guess by additional sweeps (thus a higher difficulty). But I need some ideas on what logic to use, I don't want to check every possible combination.

Thank you.


texts: Set a 2d camera's position so that a building is under the players feet

texts:
My issue is this: i am making a scrolling game in XNA, and the camera updates based on the players velocity, but the player never actually moves, he is always in the center of the screen. When he hits the top of the building though i want him to always be on top and sink through the texture in a way like this:

what i am doing to make this happen is i am just setting his velocity to 0, so its not moving, but the more velocity he hits a building with the more he sinks through it.

I also tried setting the buildings position to the plays Bounding Box's bottom, and this achieved the look i wanted but this also resulted in the other buildings rising in the air, because the velocity was still moving (even if i set it to 0).

if it was not a scrolling game, this would be not a problem, because you just set the players position to the top of the building, but because the player never actually moves, i actually need to move the camera to the point where the building is under the players feet without the other buildings rising. (Take note this is note a real camera, it is just a class that moves the objects in the world based on the players velocity). All questions are welcome.


texts:
I would like to integrate ogre3d with directx and c++ using hololens.

is it that possible to do so ?

what are the steps to convert the rendering engine, what's rendered to the frame buffer to the hololens buffer?


texts: How do I specify ARGB format textures in my input declaration?

texts:
const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::Basic32[3] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}
};

The TEXCOORD,
There is no support for a image that is ARGB. Only DXGI_FORMAT_R32G32B32A32_FLOAT

How can I load ARBG?

Or can I convert a ARGB TO A RGBA IMAGE?


texts: Specular intensity not imported from Blender into Unity

texts:
For my current project I'm using diffuse materials for my models in Blender but I do not want any Specular Intensity so I've set that to 0. Yet in Unity there is still a specular highlight and the material has a Smoothness of 0.5. Does Unity actually read Specular Intensity or am I missing some crucial detail?

I haven't been able to find any details on what the .blend-import actually reads and I can see a setting called Glossiness in the .mat-files created by Unity is set to 0.5.


texts: Why are my wheels not moving at the same speed as my car?

texts:
I need help with some wheel rotation I set up for my game. My wheels are moving 3x faster than the acceleration speed of my car. Also, I can't work out why my car is moving so slow and the brakes not working.

Have I set something in the inspector too high? I think that it might have something to do with my wheel script.

Here is a video of my problem www.youtube.com/watch?v=0YI50cJ5X4Q&feature=youtu.be

using System.Collections;
using UnityEngine;

public class Car : MonoBehaviour {
public float maxTorque = 5000f;
public float speed = 5000f;

public Transform centerofMass;

public WheelCollider[] wheelColliders = new WheelCollider[4];
public Transform[] tireMeshes = new Transform[4];

private Rigidbody m_rigidBody;

void Start()
{
    m_rigidBody = GetComponent<Rigidbody>();
    m_rigidBody.centerOfMass = centerofMass.localPosition;
}

void Update()
{
    UpdateMeshesPositions();
}

void FixedUpdate()
{
    float steer = Input.GetAxis ("Horizontal");
    float accelrate = Input.GetAxis ("Vertical");

    float finalAngle = steer * 45f;
    wheelColliders [0].steerAngle = finalAngle;
    wheelColliders [1].steerAngle = finalAngle;

    for (int i = 0; i < 4; i++)
    {
        wheelColliders[i].motorTorque = accelrate * speed * maxTorque;        }
}

void UpdateMeshesPositions()
{
    for(int i = 0; i < 4; i++)
    {
        Quaternion quat;
        Vector3 pos;
        wheelColliders[i].GetWorldPose(out pos, out quat);

        tireMeshes[i].position = pos;
        tireMeshes[i].rotation = quat;
    }
}

}


texts:
So I'm making a game which is based on randomly generated rooms and I need a way to keep the player inside them and make the player glide when he collides with the room's bounds. I currently have a SAT algorithm in place to detect collisions, but I don't know how to do collision resolution for being inside rooms.

Full code here

sf::Vector2f Collision::GetMtv()
{
    return (Mtv(small, smallestPerpendicular[smallestIndex]));
}


texts: How do I protect my rights to my game on the web?

texts:
My small games all have different gameplay. I want to showcase them through the internet. However, I'm worried about them and their concepts getting copied. How can I protect them?

Also, if I have to openly display the code to the open source community, how can I make sure I get credit for my work.


texts:
I have a problem with my enemy where when my player scrolls left the enemy scrolls with the player is there anyway to fix this even Video my full code is below its to long to fit here though

what I was trying to do is make my enemy not to change its position when my window is scrolling its doing the same for right and left keeps following the player

while runninggame:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
  [...]
# I did the same for my players key movement  this part suppose to not make my player scroll
if playerman.y < 250:
        playerman.y += 1
        for platform in platforms:
            platform.y += playerman.speed
        for enemys in enemying:
            enemys.y += playerman.speed

my enemy class

class enemy:
    def __init__(self,x,y,height,width,end):
        self.x = x
        self.y =y
        self.esright = [pygame.image.load("esright1.png"),
        pygame.image.load("esright1.png"),
        pygame.image.load("esright2.png"),
        pygame.image.load("esright3.png"),
        pygame.image.load("esright4.png"),
        pygame.image.load("esright5.png"),
        pygame.image.load("esright6.png"),
        pygame.image.load("esright7.png"),
        pygame.image.load("esright8.png"),
        pygame.image.load("esright9.png"),
        pygame.image.load("esright10.png"),
        pygame.image.load("esright11.png"),
        pygame.image.load("esright12.png"),
        pygame.image.load("esright13.png"),
        pygame.image.load("esright14.png"),
        pygame.image.load("esright15.png"),
        pygame.image.load("esright16.png"),
        pygame.image.load("esright17.png"),
                          ]
        self.esleft = [pygame.image.load("esleft1.png"),
        pygame.image.load("esleft1.png"),
        pygame.image.load("esleft2.png"),
        pygame.image.load("esleft3.png"),
        pygame.image.load("esleft4.png"),
        pygame.image.load("esleft5.png"),
        pygame.image.load("esleft6.png"),
        pygame.image.load("esleft7.png"),
        pygame.image.load("esleft8.png"),
        pygame.image.load("esleft9.png"),
        pygame.image.load("esleft10.png"),
        pygame.image.load("esleft11.png"),
        pygame.image.load("esleft12.png"),
        pygame.image.load("esleft13.png"),
        pygame.image.load("esleft14.png"),
        pygame.image.load("esleft15.png"),
        pygame.image.load("esleft16.png"),
        pygame.image.load("esleft17.png"),
                          ]
        self.esright = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esright]
        self.esleft = [pygame.transform.scale(image,(image.get_width()//3,image.get_height()//3)) for image in self.esleft]
        self.height = height
        self.width = width
        self.anim_index = 0
        self.distance = 80
        self.speed = 8
        self.vel = 3
        self.path = [x,end]
        self.walking_index = 0
        self.rect = pygame.Rect(x,y,height,width)
       def draw(self,window):
       self.move()
       if self.Walking_index + 1 >= 33:
           self.Walking_index = 0
       if self.vel > 0:
           window.blit(self.esright[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       else:
           window.blit(self.esleft[self.Walking_index//3], (self.x,self.y))
           self.Walking_index += 1
       def move(self):
       if self.vel > 0:
           if self.x + self.vel < self.path[1]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0
       else:
           if self.x - self.vel >  self.path[0]:
               self.x += self.vel
           else:
               self.vel = self.vel * -1
               self.Walking_index = 0

where I defined the enemy class

black = (0,0,0)
enemys1 = enemy(550,436,50,50,300)
enemys = [enemys1]

my full code its to long to fit here  script


texts: Resetting variables when starting a new game

texts:
What is the best practice when implementing a way to start a game when a previous game has been played and the game's variables have already some kind of values assigned to them?

The most naive answer would be to create a method that would set all the variables and objects the game uses to their default value.

However that would be obviously error prone in cases when some time later a new variable is added to the game and not added to the method where it's set to a default value - such cases could lead to impossible to track bugs when a game would work ok if started first time, but not thereafter.

This would also violate DRY principle as a variable would have a default value at two different places - in the place where it's used and in the method where it's reset.


texts: How to convey that a cutscene is about to end?

texts:
I'm currently developing a 3rd person game with dynamic cutscenes (using in-game objects instead of a pre-rendered video). During some playtesting of my game I noticed that some of my playtesters would have trouble identifying when a cutscene would end, sometimes killing them because they didn't react in time. For example:

Player walks into hallway
Cutscene start

Camera pans to look behind player
Monster drops down from the ceiling behind player
Player character starts running by itself

Cutscene end
Player expected to keep running, but doesn't know cutscene has ended so doesn't respond in time and gets killed.

My playtesters comments:

They can realize when a cutscene starts because something out of the ordinary happens (e.g. camera view changes).
They sometimes don't realize when a cutscene ends because the out of the ordinary thing doesn't change back (e.g. camera view doesn't revert to normal).

What I've tried:

To try and teach players that it's common for I used popups during the tutorial stage of the game:

Cutscene end.
Display message "Hey! Did you know you can ACTION by pressing KEY?"

I've also tried to give them examples during the tutorial where you have to be quick after a cutscene by pausing the game after the cutscene and displaying a popup, giving them time to react:

Cutscene end.
Game pauses.
Displays popup: "You're being hunted! RUN by holding SHIFT!"

Both of these methods makes the user realize (at that time) that the cutscene has ended, yet it doesn't seem to successfully teach them that this will happen in the future and they are still confused about if a cutscene has ended. I don't want to have these popups after the tutorial stage since it sort of defeats the point of tense moments.

So my question is: How can I more clearly convey to the players that my cutscene is about to end without explicitly telling them?


texts: How can I render images to multiple windows without creating double textures in SDL2?

texts:
Simply put: What is the simplest way to render an image to two different sdl2 windows?

I'm pretty new to SLD2, but I have a nice little level editor working. I then decided to move the area with edit tools to a separate window. I immediately got the following error:

  Texture was not created with this renderer.

Alas, it looks like each window needs to have its own SDL_Renderer, and each renderer needs to create its own textures for the images I want to display.

IMG_LoadTexture() needs a renderer and will only render the resulting texture to that renderer.

SDL_CreateRenderer() then needs a window as a parameter and doesn't seem to be able to ever render to another output window.

So does this really mean I have to create separate textures of each of my images for each and every renderer/window? Or is there a way to load graphics into textures that can be used by any renderer, or on any window?


texts: Can we flip znear and zfar so that positive z values increase away from the viewer?

texts:
I am confused about the projection matrix in OpenGL.

i have a habit of writing the code as follows.

glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
   glOrtho(0.0f,250.0f,0.0f,250.0f*h/w,1.0,-1.0);
else
   glOrtho(0.0f,250.0f*w/h,0.0f,250.0f,1.0,-1.0);
 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();

Simple, This code sets the viewing clipping region that maintains the equal width and height. negative z value points away from the viewer. as z value extends from 1 to -1. anything that lies outside this value wont be visible to the user.
But i have seen the code like this.

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(left,right,bottom,top,1.0, 500.0);  //how????
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -250.0f);       ///?????
glutSolidSphere(15.0f,15,15);           /// how is this visible on the screen
}

Please help me understand this code. As from my point of view the z value is totally flipped near is 1.0 its okay but zfar is 500 and following that code there is a translation of z value to -250. and drawing that sphere will be visible on the screen how? My question is can we flip znear and zfar so that positive z value will go away from the viewer.


texts:
I've a set of voxel data and I want to create a mesh out of it at run-time.

I've looked into MeshBuilder and MeshHelper but I haven't found anything useful or a good tutorial how to use them. Can anyone tell me how to create a mesh at run-time?


texts:
so i've been making a pathfinder on a grid. I've succesfuly implemented the A* algorithm so the next step is making the AI follow a path. I got it to move to the desired destination but the thing is it moves diagonally and I dont want it to. I want to move vertically or horizontally. this is my current code:

void AIEnemy::AutoMotion(Gridspot& grid)

{

std::pair<int, int> ecn = getNodePosition();

sf::Time deltaTime = clock.getElapsedTime();

std::reverse(grid.Path.begin(), grid.Path.end());

for (auto path : grid.Path)

{

float rectx = rect.getPosition().x + rect.getOrigin().x / 2,

        `recty = rect.getPosition().y + rect.getOrigin().y / 2;`
bool firm= true;

if (ecn.first == path.node.first && top >= path.rectCenter.y)

{

rect.move(0, -2);

}

if (ecn.second == path.node.second && left >= path.rectCenter.x)

{

rect.move(-2 , 0);

}

}

}

before i had a bool set that will ring true it is already in motion to so that it couldn't move in the x-axis in conjunction to th y. that didn't work, i also used if and elseif is before ut that didn't do anything.
essentially I want it to move like pacman ghosts


texts: How could I make the character sound beeps like in old school games?

texts:
I've been searching around, but I haven't found any resource on how I could achieve this, like those old school character beeps.

I want to have my characters talk with beeps like in Undertale, or Phoenix Wright, or any other games like that, but I've no luck finding anything helpful.

How could I achieve a similar effect?

Edit : Here is an example video of what i mean : https://www.youtube.com/watch?v=V5tX0GyG3_I When the text goes by, there's that deep beeping sound, that's what i meant

Edit 2 : What i mean is not how i get it to work, but rather how do i make a sound like that using a program?


texts: Winform + XNA (Microsoft Example) - Issues with Drawing Texture2D

texts:
Before I get started I would just like to say that I have been using the Microsoft Winform + Xna examples found here:

WinForms Series 1: Graphics Device

I think I somewhat understand how its working however I'm running into one major problem. I'm trying to draw a Texture2D image to the spriteFontControl's spriteBatch parameter, which is an object of the XNA SpriteBatch class, and when I do I get this red "X" on a white box that fills the entire spriteFontControl area. This is a screen shot of what it looks like:

As for the coding that I added to do this is pretty simple. I used the content parameter from the spriteFontControl to load the box.jpg image into the program. Then just called the following code inside the Draw() method for the spriteFontControl:

spriteBatch.Begin();
spriteBatch.Draw(box, new Vector2(0,0),Color.Black);
spriteBatch.End();

If anyone could please offer some help as to how to draw Texture2D images in the Winform + XNA example then that would be most helpful. I heard that it was made so that you could draw it just like you would in XNA but I think I'm still missing something.

Thanks in advance.

P.S. This is the code from the Draw() method of the spriteFontControl:

    const string message = "Hello, World!\n" +
                               "\n" +
                               "I'm an XNA Framework GraphicsDevice,\n" +
                               "running inside a WinForms application.\n" +
                               "\n" +
                               "This text is drawn using SpriteBatch,\n" +
                               "with a SpriteFont that was loaded\n" +
                               "through the ContentManager.\n" +
                               "\n" +
                               "The pane to my right contains a\n" +
                               "spinning 3D triangle.";

    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    spriteBatch.Draw(box, new Vector2(15, 15), Color.Black);
    spriteBatch.DrawString(font, message, new Vector2(23, 23), Color.White);
    spriteBatch.End();


texts: MonoGame InstancePlayLimitException on Windows w/ OpenGL

texts: Why am I getting the InstancePlayLimitException when playing several SoundEffects per second  despite there being no limit unless programming for mobile? It occurs after only a few seconds of repeated playing. I am using Visual Studio 2013 and MonoGame 3.2.


texts: Adding materials to a Line Renderer through code?

texts:
I have a material that I am using to add a glowing effect to my line renderer. I can add this as a 2nd material to the line to give it a glowing effect.

I want to be able to add/remove this material through code, so I can essentially enable/disable the effect. I have no clue how to access the current materials of the line renderer in a way that allows me to add/remove elements from the materials array. How can I do that?

Pseudocode:

private void SetGlow()
{
    line.materials.Length = 2;
    line.materials[1] = "/new/material/directory/material.mat";
}


texts: Moving a top-down camera while keeping its height constant

texts:
I'm currently writing the script for the player to explore the plane below. The camera view is set to be slightly rotated as to look down. And I have set the code to make the camera move.

This is the code, and everything is set in the update method.

        if (Input.GetKey("w"))
        {
            transform.Translate(Vector3.forward * panSpeed * Time.deltaTime);   // , Space.World if want to avoid camera going down
        }
        if (Input.GetKey("s"))
        {
            transform.Translate(Vector3.back * panSpeed * Time.deltaTime);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate(Vector3.right * panSpeed * Time.deltaTime);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate(Vector3.left * panSpeed * Time.deltaTime);
        }

The problem is that everytime that the camera goes forward, it goes straight down. And I don't want it to do that. I want to keep the "height" from the plane below to be the same as in the picture below. I want the camera to move along the red axis.

I know of the existence of Space.World in order to achieve this, but the problem is that if I do that, whenever I rotate, now the controllers are all screwed up, because if I rotate to the right for example. Now Forward (W) moves the camera to the left, Right (D), moves the camera forward, etc etc.

So basically what I need is 1: to make the camera keep the distance to the plane below while moving (not going down). and 2. To make it possible that even with rotations, the controllers are kept, and not having this weird behavior, when forward is not longer forward.

Any ideas how to achieve this?


texts: How can I develop in MonoGame without relying on .xnb files?

texts:
I'm new to game development, and MonoGame seems like a beginner-friendly framework, so thought I'd start with that. However, as I started reading tutorials on it, I noticed a common theme: That at its current state, MonoGame needs XNA's content compiler since it doesn't have one of its own. The only problem I have with this is because I'm unable to install XNA (followed instructions on the web, even installed the Game Marketplace). I'm on Windows 8.1, by the way.

Long story short, I gave up on trying to install XNA. However, I have played around a bit with MonoGame and found that you can use raw images (.png in my case) instead of those converted to .xnb. I haven't tried sound, so I don't know if it'll work. Or any other assets for the matter.

My question is, is it possible to develop in MonoGame without using .xnb files? Or, is it possible to develop without XNA's content compiler? If yes, then how?


texts: Unity C# : How to make 3D objects move in the grid?

texts:
I want to move and deploy 3D objects in the grid, like bakery 2(Storm8 Studios). How do you make a grid like that? For example, make a 5x5 grid and move it to a touchdrag. I'd like you to give me some advice.

Pictures for reference: https://lh3.googleusercontent.com/Kwp9i9ExRboeQCtM65sztw3tqEL9R76zZzB9U6j5vs98ueF9ksOU3huMdZqv4KPDZ2E=w2590-h1430


texts: View Full File Name in Project View Unity

texts:
Is there any way to view the full name of a file in Unity Project view without having to click on it?

This picture sums up my frustration:


texts: Having a list of rooms with theirs connection to each other, how do I find isolated room groups?

texts:
I'm trying to create a small roguelike and went as far as random generating rooms and corridors. Each room is an instanced object and contain an arraylist of the others rooms connected by a corridor.

I can single out unconnected rooms but how can I know the rooms that are connected only to each other but not to most of the others, forming an island?

to illustrated better the problem here is an image from the console on a bogged level. Rooms 5 and 6 are connected only to each other. What algorithm can I use to detect that?


texts: How do I use more than 32 textures in my game?

texts:
I'm building a game in OpenGL, relying on shaders as much as possible because python. However, I think I've been working under a misunderstanding of OpenGL since I started.

I've abstracted stuff into a homemade shader class/object that takes vertices and images, and turns them into VBOs and textures, and a draw() function. Not realizing there was a small limit on the GL_TEXTURE_* stuff, I was giving each one its own texture slot (as I'm thinking of them). I also hadn't yet bothered making sure the same models were using the same shader. You can see how I was running into problems.

So, just how do you deal with using more than 16/32/GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS textures in a frame? If I have floor, a player, three NPCs, four types of tree and a house, (each with unique textures) how am I going to add a fridge?


texts: With what projection matrix should I render a portal to a texture?

texts:
I'm using OpenGL. I have problem with my engine's portal implementation. To create the first portal I do:

create a virtual camera with the position of the second portal and the correct orientation
render whole scene from virtual camera to the texture using FBO
render the first portal using the texture created before.

The problem: The virtual camera is rendering to the texture with the main projection view, so when I use this texture to render the first portal, everything is rescaled. The virtual camera should only render some part of the view to prevent scaling.

The problem could perhaps be solved by changing the virtual camera's projection matrix, but I don't know how to calculate such a matrix.

Here's how it looks:

This picture shows one portal (the texture is a little bit deformed on bottom and top, but that's not important now) and some other objects. The second portal is behind the camera, and the camera is in the middle between the two portals.

We can clearly see that the portal texture is rescaled down to the portal size. As I said before, I think the virtual camera should have another projection matrix, but how do I calculate it? Or is there a better way?


texts: save a particular area of the scene as screenshot in unity

texts:
I need to save a particular part of the scene as screenshot. I have done a sample to show the particular part of the scene.

When I click on the rectangular area the selected area will being shown on the screen on a texture (marked in red rectangle):

But when I save, the whole scene is getting saved but not the selected part:

Here is code:

Texture2D screencap;
Texture2D border;
bool shot=false;
public string path;

void Start () {
     screencap=new Texture2D(300,200,TextureFormat.RGB24,false);
     border=new Texture2D(2,2,TextureFormat.ARGB32,false);
     border.Apply();
}

// Update is called once per frame
void Update () {
    if(Input.GetKeyUp(KeyCode.Mouse0))
    {
        StartCoroutine("Capture");
    }

}
string fileName(int width, int height)
{
    return string.Format("screen_{0}x{1}_{2}.png",
                         width, height,
                         System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}

void OnGUI()
{
    GUI.DrawTexture(new Rect(200,100,300,2),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect(200,300,300,2),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect(195,100,2,200),border,ScaleMode.StretchToFill);
    GUI.DrawTexture(new Rect(500,100,2,201),border,ScaleMode.StretchToFill);

    if(shot)
    {
        GUI.DrawTexture(new Rect(50,10,60,40),screencap,ScaleMode.StretchToFill);
        //Application.CaptureScreenshot(myFolderLocation+myFilename);
    }
}

IEnumerator Capture()
{
    yield return new WaitForEndOfFrame();
    screencap.ReadPixels(new Rect(198,98,298,198),0,0);
    screencap.Apply();
    shot=true;

    byte[] bytes=border.EncodeToPNG();
    string filename=fileName(Convert.ToInt32(screencap.width), Convert.ToInt32(screencap.height));
    Application.CaptureScreenshot("D:"+filename);
}

How can I save only the particular part in unity,can anybody please help me out.


texts: How can I change tags on a Steam Workshop item?

texts:
A few years ago, I posted a L4D2 modification to the game Workshop on Steam.
I'd like to be able to change the tags associated with the mod (currently, 'Weapons, UI') but it's not obvious to me how I should edit the mod profile to make this change.
If anybody can tell me how to do this, I'd appreciate it!


texts: How can I make an animation using arrays?

texts:
I want to take an array of sprites, for example

sf::Sprite animation[3] = { stepLeft, inMiddle, stepRight };

and construct an animation by looping them. Is this possible? How do I go about it?


texts: Bullets Are Spawning Weirdly in my Java/LibGDX Plane Shooting Game

texts:
What I'm trying to do

Have bullet's spawn in the center ( or close enough, the exact number can be played with after ) of my player sprite.

What's going wrong:

They're spawning super weirdly. The first one always spawns at the bottom left corner. Than they spawn all over the place though not completely random. If I shoot on only the right side of the screen, bullets don't spawn on the left side.

How I'm doing it:

Creating a New Bullet and Managing them , Methods:

Method Placement:

Drawing (In Batch):

Also:

I know that I'm not using LibGDX arrays, or objects, or array of objects, or sprites for the bullets. ( I used sprites for the player ) though I was going through confusing complications and this strategy with batch drawing seems inefficient but simplified for my development ability.

I also haven't made a bullet disposal/reset system yet. I'm still working on this part first.

Anyone know what I'm doing wrong or a solution?

EDIT: ManageBullets is just so the bullet's go up once they spawn. ( Shooting )


texts: Tile Collision - subtracting a minor value to the box size

texts:
I'm having a certain problem when doing collision checks on bounding boxes that have their edges aligned with upper or right tiles. It shouldn't count as an intersection but I don't know a good solution for this.

Let's say the player is centered with some tile with that has no collision and the 8 surrounding tiles do have collision. The problem that happens here is that my collision check function will still report a collision because the upper and right edges of the square are in touch with the other tiles. The lower and left are too, but they won't collide:

I check the collision using the center and size, x and y, for the box.

bool isColliding( float centerX, float centerY, float sizeX, float sizeY );

So in this image, the player would be centered at ( 1.5, 1.5 ), relatively to tiles, and his size would be 1 tile x and y. That makes him centered in tile ( 1, 1 ). And when we do the math his left and lower limits are 1, so his limits are within tile ( 1, 1 ), but his upper and right limits are 2 so it reports an intersection with those tiles (the darker ones in the picture).

This happens because I calculate half sizes:

float halfSizeX = sizeX / 2.0f;

And the left limit would be

int leftLimit = centerX - halfSizeX;

In this case the player is not supposed to be intersecting any tile, so my quick fix was to subtract a very small value to the half size like this:

float halfSizeX = sizeX / 2.0f - 0.001f;

So the right limit will be 1.999f or so, and won't actually be 2. And this will work as this is only done in the collision checking, not in correcting the position, and all amounts of movement are bigger than 0.001 tiles which would be the biggest concern.

But I don't really like this solution, it looks kind of dirty.. My questions is, is there any good alternative to subtracting this value out of the blue?

EDIT:

As asked below in the comments I'm posting the code:

bool Map::isColliding( float centerX, float centerY, float sizeX, float sizeY )
{
    float halfSizeX = sizeX / 2.0f - 0.001f;
    float halfSizeY = sizeY / 2.0f - 0.001f;

    int fromX = (int)max( centerX - halfSizeX , 0.0f );
    int toX = (int)min( centerX + halfSizeX, (float)getNumTilesX() );

    int fromY = (int)max( centerY - halfSizeY , 0.0f );
    int toY = (int)min( centerY + halfSizeY, (float)getNumTilesY() );

    for ( int x = fromX; x <= toX; ++x ) {
        for ( int y = fromY; y <= toY; ++y ) {
            if ( getTile( x, y )->hasCollision() ) {
                return true;
            }
        }
    }

    return false;
}


texts: Nothing happens when I press play in Unity3D

texts:
Hello everyone I am making my first game, things were going well but suddenly nothing happens when I press play, I have already update to the newest unity version but it persists.

I have the main camera selected, layers seem fine, I rested the camera position and also tried to switch to 3d view. Do you have any idea on how to fix this?

You can download the game project file here: https://www.dropbox.com/s/0c64y0ats33f79i/Energy%20Manager.rar?dl=0

Any help is very much appreciated.


texts: Why does my Enemy A.I stop moving when it hits the wall, and how to fix it?

texts:
I am making my 2D platformer game at the moment, and I am still a beginner. I saw this tutorial on youtube in which he showed how to make an enemy a.i move. He manages to move it but he didn't show how to flip the enemy once it hits the wall because when it does, it doesn't move. How do I fix this?

Ps: He used a gameObject to flip the enemy.

Here is an example of the error I am facing

Enemy Script

public float speed;
public float distance;
private bool movingRight = true;
private Rigidbody2D myBody;
public Transform groundDetection;
public LayerMask ground;

private void Start()
{
    groundDetection = this.transform;
    myBody = GetComponent<Rigidbody2D>();
}

void Update()
{
    transform.Translate(Vector2.right * speed * Time.deltaTime);

    RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 2f, ground);

    if (groundInfo.collider == false)
    {
        if(movingRight == true)
        {
            transform.eulerAngles = new Vector3(0, -180, 0);
            movingRight = false;
        }
        else
        {
            transform.eulerAngles = new Vector3(0, 0, 0);
            movingRight = true;
        }
    }
}


texts: InvalidCastException when instantiating a prefab on the network using Photon

texts:
As stated in the title, I get this error when I try to instantiate a game object using Photon:

InvalidCastException: Cannot cast from source type to destination type.
NetworkingPeer.DoInstantiate (ExitGames.Client.Photon.Hashtable evData, .PhotonPlayer photonPlayer, UnityEngine.GameObject resourceGameObject) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/NetworkingPeer.cs:3069)
PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group, System.Object[] data) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs:2493)
PhotonNetwork.Instantiate (System.String prefabName, Vector3 position, Quaternion rotation, Int32 group) (at Assets/Photon/Photon Unity Networking/Plugins/PhotonNetwork/PhotonNetwork.cs:2437)
GunController.EquipGun (.Gun gunToEquip) (at Assets/Scripts/Gun/GunController.cs:38)
GunController.init () (at Assets/Scripts/Gun/GunController.cs:19)
NetworkPlayer.Start () (at Assets/Scripts/Network/NetworkPlayer.cs:20)

Old, working code:
equippedGun = Instantiate(gunToEquip, weaponHold.position, weaponHold.rotation) as Gun;
equippedGun.transform.parent = weaponHold;

New code, using Photon:
equippedGun = PhotonNetwork.Instantiate(gunToEquip.name, weaponHold.position,
                                        weaponHold.rotation, 1).GetComponent<Gun>();
equippedGun.transform.parent = weaponHold;

(I do GetComponent, as normal instantiate returns Object and PhotonNetwork.Instantiate returns GameObject)

equippedGun is by default an empty variable of type Gun

gunToEquip is again a Prefab variable of type Gun that gets passed into the function. (PhotonNetwork.Instantiate takes in the name of the prefab, not the actual prefab, thus gunToEquip.name)
In this particular case, gunToEquip is the default gun that fails to instantiate, which is set by the unity inspector

weaponHold is just a transform variable, again set by the inspector.

I somehow managed to fix it for my player prefab, I have no idea how. I was just changing and reverting stuff until it magically worked. How can I resolve this error?
Not sure if it is the problem, but I've attached the prefab settings:


texts: (Unity) Proper way to save ScriptableObjects changed during play mode?

texts:
I was wondering what the "correct" way to save scriptable objects in Unity that are changed during Play mode. So far I have something that works:

    // changes
    PartyMember Lalala = PartyMemberDictionary.Find("Lalala");
    Lalala.HP += 17;
    print("Lalala's HP: " + Lalala.HP);
    // then saves
    AssetDatabase.Refresh();
    EditorUtility.SetDirty(Lalala);
    AssetDatabase.SaveAssets();

Note: Lalala is a direct reference to a PartyMember scriptable object in my Assets/Resources folder.

I'm still a little shaky on this approach, however. I got this directly from reading this question:

https://forum.unity3d.com/threads/scriptableobject-asset-problem-the-changes-wont-saved-to-disk.229664/

But the commentator did not explain what each of these three lines of code mean.

    AssetDatabase.Refresh();
    EditorUtility.SetDirty(Lalala);
    AssetDatabase.SaveAssets();

Can someone explain these to me? I'm not sure I understand them fully. I assume "dirty" indicates that data changed; please correct me if I'm wrong.

In this link

https://docs.unity3d.com/ScriptReference/AssetDatabase.SaveAssets.html

it asserts that SaveAssets() saves all unchanged asset changes to disk, so why do I need the other Refresh and SetDirty Functions?

In this link

http://answers.unity3d.com/questions/11531/why-doesnt-my-scriptableobject-save-using-a-custom.html

The OP says "as I found out after some trial and error AssetDatabase.SaveAssets doesn't actually save the asset as expected." ... so confused at this point. That leaves me hesitant to continue until I understand what's going on. Perhaps the Refresh and SetDirty cement the job?

Also,
in this link

https://docs.unity3d.com/ScriptReference/EditorUtility.SetDirty.html

it mentioned that Undo.RecordObject is preferred. Based on your experiences, is this true? Is EditorUtility.SetDirty(); obsolete in this day and age already? I don't want to use it if I have to change my code in the future.

At the end of the day I simply want something that works.


texts:
I am pretty new to Graphics Programming. I am currently using OpenGL.
I have got some hands-on in last few days. I have knowledge of Texture Mapping, Cubemap, Multitexturing. But somehow I am not able to bridge the gap between my understanding and actual coding

What I am trying to do is create a demo of a stars coming out of screen. It should look realistic.

Now, my questions are:
1. Is Cubemap capable of doing this?
2. Do I need to write particle engine for this?(Really, don't want to at this stage)
3. This is kinda most needed for me. May I See some code..? In some tutorial / just code would also do.. but i think if its similar to my requirement then only it will Help


texts:
I'm starting with LibGDX and I loving it so far, but I have found some troubles and I'm getting a little frustrated. I've searched a lot for a solution and tried many things, but nothing seems to work. What I want to accomplish is basically a 2d map with a rts-like camera, in other words, a map/world bigger than the viewport where I can move the camera freely. The problem is I can't make the camera move, and I'm not even sure if my world is bigger than my viewport. How can I get these two things done? I'm sure I'm doing something wrong, but I can't figure what it is. Any help would be really appreciated.

These are my classes:

GameMain

public class GameMain extends Game {

private SpriteBatch batch;

@Override
public void create () {
    batch = new SpriteBatch();
    ScreenManager.getInstance().initialize(this);
    ScreenManager.getInstance().showScreen(ScreenEnum.WORLD);
}

@Override
public void render () {
    super.render();
}

public SpriteBatch getBatch() {
    return this.batch;
}
}

AbstractScreen

public abstract class AbstractScreen extends Stage implements Screen {
protected AbstractScreen() {
    super(new ScreenViewport(new OrthographicCamera()));
}

// Subclasses must load actors in this method
public abstract void buildStage();

@Override
public void render(float delta) {
    // Clear screen
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // Calling to Stage methods
    super.act(delta);
    super.draw();
}

@Override
public void show() {
    Gdx.input.setInputProcessor(this);
}

@Override
public void resize(int width, int height) {
    getViewport().update(width, height, true);
}

@Override public void hide() {}
@Override public void pause() {}
@Override public void resume() {}
}

ScreenEnum

public enum ScreenEnum {

WORLD {
    public AbstractScreen getScreen(GameMain game, Object... params) {
        return new WorldScreen(game);
    }
};

public abstract AbstractScreen getScreen(GameMain game, Object... params);
}

ScreenManager

public class ScreenManager {

// Singleton: unique instance
private static ScreenManager instance;

// Reference to game
private GameMain game;

// Singleton: private constructor
private ScreenManager() {
    super();
}

// Singleton: retrieve instance
public static ScreenManager getInstance() {
    if (instance == null) {
        instance = new ScreenManager();
    }
    return instance;
}

// Initialization with the game class
public void initialize(GameMain game) {
    this.game = game;
}

// Show in the game the screen which enum type is received
public void showScreen(ScreenEnum screenEnum, Object... params) {

    // Get current screen to dispose it
    Screen currentScreen = game.getScreen();

    // Show new screen
    AbstractScreen newScreen = screenEnum.getScreen(game, params);
    newScreen.buildStage();
    game.setScreen(newScreen);

    // Dispose previous screen
    if (currentScreen != null) {
        currentScreen.dispose();
    }
}
}

WorldScreen

public class WorldScreen extends AbstractScreen {

private GameMain game;
private Texture map;

public WorldScreen(GameMain game) {
    this.game = game;
    map = new Texture("sprites/maps/map.jpg");
}

@Override
public void buildStage() {

}

@Override
public void show() {

}

@Override
public void render(float delta) {
    super.render(delta);

    game.getBatch().begin();
    game.getBatch().draw(map, 0, 0);
    game.getBatch().end();
    this.getCamera().translate(+500, +500, 0);
    this.getCamera().update();
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

I debugged the camera and it's changing its value position, but it's not being reflected in the screen.

Also, is there a way to prevent the map texture from being scaled when resizing?


texts: 2D World - How to represent my Game Objects graphically?

texts:
I want to code my own topdown 2D game with SFML+C++ that later shall have multiplayer functionality. Therefor I want to seperate the graphical and logical Parts of my game.
All of my ingame Objects are thought to have Polygon-Hitboxes as their physical representation. What I now need is a graphical Representationn to draw them onto the Screen... I dont want to use tiles, because I want to have Support for rotated objects to and my Objects Are not evenly distributed so they wouldnt fit a grid.

My Question now is what would be the best way to graphically represent my Objects?

I thought of some ways but am not sure how you would ''normally'' do sth like that :)

Thought 1: As I only need two layers (For now(Floor and Things that you can collide with)) I thought my Floor could consist of tiles and then I draw my other Objects as sf::RectangleShapes or sf::Sprites onto it. (I would mix sprites and a more flexible approach here)

Thought 2: I only take sprites and include the objects that are ontop into each sprite that they should be drawn onto. (I think that it gets too messy and doesnt really ''solve'' my Problem)

Thought 3: I take each Object (Box, Part of the Floor(maybe each brick?)) and create an own textured sf::ConvexPolygon or sf::Rectangle  for them. (Idk how big the impact on performance would be there)

PS: My approaches might seem a bit weird because I recently worked much with 3D-Software(eg Blender) and so I think of every Object to be a (2D) Mesh of Polygons that needs to be textured :)

I hope some of you can provide me some clarity on how to solve my Question :)


texts: Can't get to work Spritefonts on monogame 3.5(using Visual Studio 2015 Comunity)

texts:
I've been trying to get to work spritefonts, but to no avail. I've added the pipefont to the Pipeline

but when I try to load it, it shows this error here

Here it is the spritefont content

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

<!--
Modify this string to change the font that will be imported.
-->
<FontName>Arial</FontName>

<!--
Size is a float value, measured in points. Modify this value to change
the size of the font.
-->
<Size>12</Size>

<!--
Spacing is a float value, measured in pixels. Modify this value to change
the amount of spacing in between characters.
-->
<Spacing>0</Spacing>

<!--
UseKerning controls the layout of the font. If this value is true, kerning information
will be used when placing characters.
-->
<UseKerning>true</UseKerning>

<!--
Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic",
and "Bold, Italic", and are case sensitive.
-->
<Style>Regular</Style>

<!--
If you uncomment this line, the default character will be substituted if you draw
or measure text that contains characters which were not included in the font.
-->
<!-- <DefaultCharacter>*</DefaultCharacter> -->

<!--
CharacterRegions control what letters are available in the font. Every
character from Start to End will be built and made available for drawing. The
default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin
character set. The characters are ordered according to the Unicode standard.
See the documentation for more information.
-->
<CharacterRegions>
  <CharacterRegion>
    <Start>&#32;</Start>
    <End>&#126;</End>
  </CharacterRegion>
</CharacterRegions>

Any ideas?


texts: XNA UV Mapping flipping the Texture every second time

texts:
I am making a tile based game. Recently I moved to drawing tiles as primitives to speed up things and also allow for easier lighting (Vertex Shader).

I then took it a step further and made some calculations to "merge" together tiles into the same primitive to gain even more performance, and to get around UV texture problems I simply did this...

if (!top)
{
    //Adds the top vertices
    thisquad.Vertices[0] = new VertexPositionTexture(new Vector3(new Vector2(p.X, p.Y), 0), new Vector2(0, 0));
    thisquad.Vertices[1] = new VertexPositionTexture(new Vector3(new Vector2(Tile.Size + p.X, p.Y), 0), new Vector2(1, 0));
    top = true;
}
//Extends the bottom vertices
thisquad.Vertices[2] = new VertexPositionTexture(new Vector3(new Vector2(p.X, Tile.Size + p.Y), 0), new Vector2(0, currentquadtilecount));
thisquad.Vertices[3] = new VertexPositionTexture(new Vector3(new Vector2(Tile.Size + p.X, Tile.Size + p.Y), 0), new Vector2(1, currentquadtilecount));
currentquadtilecount++;

With currentquadtilecount starting at 1, if a tile is floating on its own it will display the texture properly, but for every second tile that merges, the texture is flipped. As shown below...

What am I doing wrong? Is this even the right way to do this??

Twitchy


texts: Blender & Unity - Move texture with Bone in way that works with Unity?

texts:
I created a character model in Blender with non-spherical eyes. The only way I can make the eye movement look good is if I move the pupil Image Textures along the eye meshes.

The way I've achieved the pupil movement in Blender is with modifiers, which Unity apparently doesn't work with. I've tried "UV Warp" controlled by bone and "UV Project" controlled by bone, and moving the eye bones in Unity does nothing.

So, I'm kind of stumped and desperate for something that will work for my use case. Any ideas that will be Unity-friendly, please?


texts: How to mirror/reflect/flip a 4D transformation matrix

texts:
I am importing my animation keyframe joint data from Blender to my game engine. The joint data is a set of 4D matrices. Things are looking good except a remaining issue where the animation is facing the opposite direction than expected.

The matrices are column major, left handed coordinate systems. Y is up. I essentially need to reflect all the joints on the the Z axis. A rotation around the Y axis will not be enough because there are translation transformations that need to be mirrored as well.

Edit: I am looking for the math on how to do this in the engine and not from Blender.


texts:
I really want to know how the bullets in Radiangames Inferno are done. The bullets seem like they are just billboard particles but I am curious about how their tails are implemented. They can curve so this means they are not just a billboard. Also, they appear continuous which implies that the tails are not made of a bunch of smaller particles (I think).

Can anyone shead some light on this for me?


texts: How do I create an actor class in UDK that will spawn a specific particle system?

texts:
I'm trying to write a new class that I can drag from actor classes window into the scene and it will spawn a specific particle effect. Its going to be a 'prop' that later will also contain a static mesh and a point light. Maybe some defined variables that can be changed in the properties window. So far, I have the static mesh working using this code:

class LightFixture extends StaticMeshActor;

defaultproperties
{
    Begin Object Class=StaticMeshComponent Name=myMesh
        bAllowApproximateOcclusion=TRUE
        bForceDirectLightMap=TRUE
        bUsePrecomputedShadows=TRUE
        StaticMesh=StaticMesh'props.Meshes.lamp'
    End Object

    Components.Add(myMesh)
}

now, I'd like to add a particle system (template?), and from what I'm learning, it's not as easy as adding the mesh. In a new class, I tried to add a particle effect this way:

class FireParticle extends EmitterPool
placeable;

var ParticleSystemComponent PSC;

defaultproperties
{
    Begin Object Class=ParticleSystemComponent Name=myEffect
        bAutoActivate=true
        Template=ParticleSystem'props.FX.fire'
    End Object

    ParticleSystemComponent=myEffect
    Components.Add(myEffect)
}

So that didn't work... I read somewhere that emitterpool was the way to spawn.. I am very new to scripting, if that isn't already obvious :)

thanks in advance, if anyone can help..


texts: Any idea why my openGL camera is stuttering only on the X axis? and only when using nvidia drivers?

texts:
As part of my assignment, I've been building a scene graph framework in C++/OpenGL.

My camera works absolutely fine going backwards and forwards, but when I strafe / move on the X axis, the camera just starts stuttering. It doesn't make much sense to me, because it's the same principle to move back/forward as it is to move right/left.

Everything is also normalised and being applied by deltaTime, so that's not an issue. Interestingly, this didn't happen when I was using my intel built in gpu, but only started occurring when I forced my nvidia card to handle the program.

Here is a video of the aforementioned stutter: https://www.youtube.com/watch?v=DyTIv0yiaP0&feature=youtu.be

My scene graph is available for viewing on my GitHub:

The repo: https://github.com/charliegillies/fullmetal.
The camera https://github.com/charliegillies/fullmetal/blob/master/fullmetal.cpp (line 503-730, mostly get/set methods.)
The camera controller https://github.com/charliegillies/fullmetal/blob/master/fullmetal-helpers.cpp (line 14-204)

Please note that this framework is still in its early days.

Let me know what you think, and I'll be sure to post a fix if I find it.


texts: How to implement a system like the draft from NFL/NHL/NBA for an mmo?

texts:
I want to build a soccer manager mmo and I'm currently thinking about how to get young players into the game.
The classic way would be to invest into the youth and produce better youth players each season. But that's kinda oldschool.
I'd rather implement a draft-like system that has a pool of young players and the teams can choose one of them.
Now since the users aren't necessarily online when they should be, it needs to be built in a way, that the draft takes place maybe over the whole season, but the players are available to the teams the season after.
There are a couple of questions that still need to be answered.
Like how to handle multiple leagues? Can all choose from the same pool or does every league have its own pool of players to choose from?
How would you do it?


texts: Is it possible to capture screenshots in headless (no graphics) mode in unity?

texts: I am trying to capture screenshots while running unity simulation in headless mode (no graphics), if anybody tried to do the same and it worked, please share how could you make it work.


texts: How do games that generate the world by noise handle physics on the server?

texts:
I keep thinking about what it is like to do the physics on the server, so that it is authoritative, and thus avoid cheating, in a game that manages the world by noise, ie the collisors are being generated from the player walking. If the server also generates the world, how do you deal with several players? I can not imagine that it manages the server-side world to give the last word, because if a player is far from each other, they would be in different chunks, so the game would have to run the algorithm to generate for each of those chunks.

Or is it simply ignored, and the server is not authoritative in this type of game (minecraft, terraria, No Man's Sky, or any other that generates logic by noise)?

The problem of not doing this on the server is that players can cheat and send what features are where they are not or which mountains no longer collide among others.


texts: Convert array of object to json in unity

texts:
I need to convert the array of object to json. I have written code to convert object to json. How can I convert the object array to json format

JSONClass jsonClass = new JSONClass ();

    jsonClass ["Array"] = Array;
    jsonClass ["Array"] = new JSONClass ();
    jsonClass ["Array"]["Value1"] = 1;
    jsonClass ["Array"]["Value2"] = 1;
    print (jsonClass.ToString(""));

How to convert this to below format

Here is my expected output

    "Array": [
          [
        "Value1",
          1,
         ]
         [
        "Value2",
          5,
         ]

    ]


texts: High quality specular reflections on Android

texts:
I opened the Unreal Editor VR example, imported the TwinMotion materials and set the floor to a nice parquet. In the editor it looks like this:

However when I run it on my Oculus Quest it looks like this:

It's a little hard to see in this example because of the weird artefact on the floor, but the reflections are much lower quality. It seems like the bump maps aren't being used at all.

Is there any way to fix that? (Bonus points if you can tell me what is going on with the grey overlay, which doesn't show up in the preview.)


texts: Instantiate prefab randomly but not in already occupied position

texts:
I want to generate bubbles randomly on screen. When a bubble is generated in one place then other bubbles should not be generated near its radius 1 area, so they can not collide or trigger with any other bubbles.

How can I do it ?

public void GenerateBubble ()
{
    newBubbleXPos = Random.Range (-7, 7);
    newBubbleYPos = Random.Range (-3, 3);
    bubbleClone = (GameObject)Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity);
    UIManager.instance.ChangeBubbleSprite (bubbleClone);
    bubbleList.Add (bubbleClone);
    if (bubblePosList.Contains (bubbleClone.transform.position)) {
        bubbleClone.transform.position=new Vector3(Random.Range (-7,7),Random.Range (-3,3),0);
    }
    bubblePosList.Add (bubbleClone.transform.position);
    bubbleClone.transform.parent = UIManager.instance.CurrentLevel.transform;
    GLOBALS.bubbleCounter++;
}

In this code every bubble is generated in a different position, but they can collide with other bubbles.  I want to generate new bubbles not at the same position. My bubble colliders's radius is 1.


texts: Where and how to promote an HTML5 game engine?

texts:
I've recently completed an engine, called Irenic.

Now, I was wondering, how could one promote it? The process surely is different than promoting a game, because a game can be played by almost anyone, and a game engine can be used only by developers. Aside from obvious things such as posting on Gamedev.net, are there some lists or wikis I could post it to? Other ways?

I'm not really interested in people using my engine, but rather giving some feedback and so on. Just getting it out there would be cool.


texts:
I am stuck on the code for couple of days but couldn't figure it out. Therefore I turned out to look the answer here but couldn't find any that match the requirement Hope some One might help

here is the code

/*  Part1
 *Step Horizontal Movement
 * Use to get left and right movement
 */
if(Input.GetKey ("right")||Input.GetKey ("left")){
    moveDir.x = Input.GetAxis("Horizontal"); // get result of AD keys in X
}
rigidbody.velocity = moveDir * speed;

/*Part2
 *Continuse Forward Movement
 */
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
    moveDir.z = Input.GetAxis("Vertical");
    rigidbody.AddRelativeForce(moveDir*50);
}

I have a Cube with added rigidBody Component. When pressed left or right key the cube should move in that direction and when key is released it should stop Part one when run commenting part2 code runs correctly

the other movement that I am trying to achieve is the cube should move continuously.But the thing is when pressed up key it should increase the magnitude and when released it should maintain the magnitude and move constantly.This is also achieved successfull with the part2 code by commenting part1 code But when but run without commenting any of them part1 results are correct but part2 does not provide correct result which was obtained by commenting part1 code

Is there any other way to obtain the same reult


texts:
My room is bigger than my UMA character so on spawn my character looks tiny. I have found this link: http://answers.unity3d.com/questions/988134/uma-how-to-increase-npc-avatar-scale.html

but everywhere I put my code, it does not change my avatars features. Here is my code:

using UnityEngine;
using System.Collections;
using UMA;

public class UMACreator1 : MonoBehaviour {
    public UMAGeneratorBase generator;
    public SlotLibrary slotLibrary;
    public OverlayLibrary overlayLibrary;
    public RaceLibrary raceLibrary;
    public RuntimeAnimatorController animator;

    [Range(0.0f, 1.0f)]
    public float bodyMass = 0.5f;

    private UMADynamicAvatar umaDynamicAvatar;
    private UMAData umaData;
    private UMADnaHumanoid umaDnaHuman;
    private UMADnaTutorial umaDnaTutor;

    private int numberOfSlots = 20;

    void GenerateUMA()
    {

        GameObject go = new GameObject("MyUMA");
        umaDynamicAvatar = go.AddComponent<UMADynamicAvatar>();

        umaDynamicAvatar.Initialize();
        umaData = umaDynamicAvatar.umaData;

        umaDynamicAvatar.umaGenerator = generator;
        umaData.umaGenerator = generator;

        umaData.umaRecipe.slotDataList = new SlotData[numberOfSlots];

        umaDnaHuman = new UMADnaHumanoid();
        umaDnaTutor = new UMADnaTutorial();
        umaData.umaRecipe.AddDna(umaDnaHuman);
        umaData.umaRecipe.AddDna(umaDnaTutor);

        CreateMale();

        umaDynamicAvatar.animationController = animator;

        umaDynamicAvatar.UpdateNewRace();

        go.transform.parent = this.gameObject.transform;

        go.transform.localPosition = Vector3.zero;
        go.transform.localRotation = Quaternion.identity;

     }

     void CreateMale()
     {
        var umaRecipe = umaDynamicAvatar.umaData.umaRecipe;
        umaRecipe.SetRace(raceLibrary.GetRace("HumanMale"));

        umaData.umaRecipe.slotDataList[0] = slotLibrary.InstantiateSlot("MaleFace");
        umaData.umaRecipe.slotDataList[0].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead02"));

    umaData.umaRecipe.slotDataList[1] = slotLibrary.InstantiateSlot("MaleEyes");
    umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlay"));

    umaData.umaRecipe.slotDataList[2] = slotLibrary.InstantiateSlot("MaleInnerMouth");
    umaData.umaRecipe.slotDataList[2].AddOverlay(overlayLibrary.InstantiateOverlay("InnerMouth"));

    umaData.umaRecipe.slotDataList[3] = slotLibrary.InstantiateSlot("MaleTorso");
    umaData.umaRecipe.slotDataList[3].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBody02"));

    umaData.umaRecipe.slotDataList[4] = slotLibrary.InstantiateSlot("MaleHands");
    umaData.umaRecipe.slotDataList[4].SetOverlayList(umaData.umaRecipe.slotDataList[3].GetOverlayList());

    umaData.umaRecipe.slotDataList[5] = slotLibrary.InstantiateSlot("MaleLegs");
    umaData.umaRecipe.slotDataList[5].SetOverlayList(umaData.umaRecipe.slotDataList[3].GetOverlayList());

    umaData.umaRecipe.slotDataList[6] = slotLibrary.InstantiateSlot("MaleFeet");
    umaData.umaRecipe.slotDataList[6].SetOverlayList(umaData.umaRecipe.slotDataList[3].GetOverlayList());

    umaData.umaRecipe.slotDataList[3].AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01"));
    umaData.umaRecipe.slotDataList[5].AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01"));

    umaData.umaRecipe.slotDataList[0].AddOverlay(overlayLibrary.InstantiateOverlay("MaleEyebrow01",Color.black));

}

// Use this for initialization
void Start () {
    GenerateUMA();
}

// Update is called once per frame
void Update () {
    if(bodyMass!=umaDnaHuman.upperMuscle)
    {
        SetBodyMass(bodyMass);
        umaData.isShapeDirty = true;
        umaData.Dirty();
    }
}

void SetBodyMass(float mass)
{
    umaDnaHuman.upperMuscle = mass;
    umaDnaHuman.upperWeight = mass;
    umaDnaHuman.lowerMuscle = mass;
    umaDnaHuman.lowerWeight = mass;
    umaDnaHuman.armWidth = mass;
    umaDnaHuman.forearmWidth = mass;
}
}

And here's the image. I want him to be as big as the chair


texts:
So I'm currently writing the engine for my videogame. I've almost integrated Tiled (I think) so I should have a map-creator here soon.

My question is, how do I actually make the grid? I'm really confused here. If I create a large map with, say, 20x20 grids the size of 32x32 (screen size 640x640), then what do I do with it?

Let's say I have the code for creating a window, and then place a player sprite that I can move with input, that's fine. If I use one map that's as big as the screen, then every pixel on the map is also a pixel on the game screen. The mapping is exact.

Now what happens if I have a 2000x2000 map, for example? My character would have to keep moving and move the map around (or rather the camera focused on the player moves). Then I can no longer say that the screen maps exactly to the pixel position of the map.

I tried making a Grid class that maps out the screen area to 32x32 tiles, but I'm not sure if that makes any sense. Once the map moves each tile would have to update its information, or something. I'm just really confused here.

How do I actually make the tiles and a grid and map them to the data I get from tiled, or that I make myself? Are there any good examples of source code that I could look at?


texts: MMO Client / Server Architecture (NoSQL)

texts:
The main aim is to keep the games variables server-side for obvious security reasons.
I believe having server-side code to check before updating the games database values will protect me from classic game hacking methods.

To avoid clients sending direct updates to the database, the server first validates the clients requested actions.

The database keeps track of every Mobile & Item

The Server has all the game-logic

The clients simply render and work as controllers that send the server actions that wont occur unless validated by the servers logic.

Clients should only send the server "Action Request"

Server then checks the "Action Request" with two possible outcomes :

Valid Request : Update DB and Re-send updated data to Clients for post-processing.
Invalid Request : Notify the client that the Request was invalid.

I need to know if im thinking in the right tracks.
Thanks.


texts:
So... I am theorizing the development of a 2d living persistent fullsized world with simulated ecossystem, etc..., and many, many objects, but how can I handle the giant amount of data that will be calculated per instance.
I mean, as the ecossystem is simulated and alive, animals would roam, plants would grow the climate would change etc... I already planned on how to implement the simulated ecossystem, but I wanted them to happen all at once, not in separated instances like World of Warcraft's dungeons or different maps. Just one entire and fullsized chunck with all the things happening on it.

Is it possible, even for an extreme low graphical game? I know of games that do something like it. Eg.: Dwarf Fortress, but what I am aiming for is way bigger than that.

EDIT:
For the "AI", I was planning on do behavioral intelligent organization or BIO, something I am planning and theorizating. It would be like a giant The Sims, every object(animal, plant, etc...) would have it's needs, characteristics, possibilities and impossibilities, they need to eat so they interact with the enviroment and with other objects on their own with modified version of A* lead by his senses(vision, audition, ect...). I know it is complicated and not polished, its because I am still studying everything and I'm more like a amateur programmer.


texts: Will using similar/exact name to a current Marvel superhero name for your game be a problem?

texts:
I have heard that the word 'superhero' is trademarked by marvel and DC and thus we can't use superhero as part of the name of a game we develop. But I wonder do they also have exclusibe rights to all the names of their super hero characters?

For example will people get in trouble if they name their games 'premagneto', 'superwolverine', 'exbeyonder' or 'the cyclop'?


texts: What torque should I apply in Bullet to maintain a vertical orientation?

texts:
I have a RigidBody in Bullet. Each frame, I want to apply torque to correct its orientation toward an upright position (i.e. near-zero pitch and roll). I know its angular velocity and orientation.

Bullet is not very well documented. I don't even know what the parameters to btRigidBody::applyTorque() mean.

How should I approach this?


texts: Method of handling audio and memory in game

texts:
I've started coding a new game project and I've implemented Ogre for the graphics rendering and begun thinking about the audio side of things.

I was considering using the SFML audio component for implementing audio. It is cross platform and can handle streaming music from the file or playing sounds loaded into memory from a buffer.

My initial thoughts were along the line of creating an audio manager class that can load all the relevant sounds into memory and then just be able to play them by reference when required. My concern there was the potential memory use of having a whole lot of sounds loaded into memory.

This is the code I came up with as a very rough test of what I was thinking. Obviously it would need to be improved a lot but it does seem to work.

#include <vector>
#include <string>
#include <iostream>
#include <unistd.h>

#include <SFML/Audio.hpp>

class gameSound
{
public:
gameSound();
~gameSound();

bool loadSound(std::string filename);

std::string name;
sf::SoundBuffer buffer;
sf::Sound sound;
};

gameSound::gameSound(){}
gameSound::~gameSound(){}

bool gameSound::loadSound(std::string filename) {
if(!buffer.loadFromFile(filename))
    return false;

sound.setBuffer(buffer);

return true;
}

class SoundManager
{
public:
SoundManager();
~SoundManager();

void PlaySoundByName(std::string name);
void AddSound(gameSound* snd);

std::vector<gameSound*> sounds;
};

SoundManager::SoundManager(){}
SoundManager::~SoundManager(){

while(!sounds.empty())
{
    sounds.pop_back();
}

}

void SoundManager::AddSound(gameSound* snd) {
sounds.push_back(snd);
std::cout << "gameSound added with name: " << snd->name << " total sounds : " << sounds.size() << std::endl;
}

void SoundManager::PlaySoundByName(std::string name) {

for(std::vector<int>::size_type i = 0; i != sounds.size(); i++) {
    if(sounds[i]->name == name) {
        std::cout << "Match found for " << name << std::endl;
        sounds[i]->sound.play();
    }
}

}

int main()
{

SoundManager* smgr = new SoundManager();

gameSound* s1 = new gameSound();
s1->loadSound("sound.ogg");
s1->name = "Sound";

gameSound* s2 = new gameSound();
s2->loadSound("alarm.ogg");
s2->name = "Alarm";

gameSound* s3 = new gameSound();
s3->loadSound("dog-grunt.ogg");
s3->name = "DogGrunt";

smgr->AddSound(s1);
smgr->AddSound(s2);
smgr->AddSound(s3);

smgr->PlaySoundByName("DogGrunt");

sleep(2);

smgr->PlaySoundByName("Alarm");

sleep(2);
return 0;
}

I know with most systems these days, especially gaming systems, there is usually plenty of memory so it might not be an issue. I was considering implementing a way to load the most important sounds into memory for instant access and then have less common sounds loaded and freed from memory as they are required.

I am interested to know how others have approached the handling of audio required for a game and if I am on the right track.


texts:
I have tried achieving a good delta time and fps counter over the last few days, read and watched a lot about it, but still can't seem to get it to work.
Here is an example:
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>

int main(int argc, char* argv[]) {

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        printf("error initializing SDL: %s\n", SDL_GetError());
    }

    SDL_Window* window = SDL_CreateWindow("Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 900, SDL_WINDOW_SHOWN);

    if (!window) {
        printf("error creating window: %s\n", SDL_GetError());
    }

    Uint32 renderFlags = SDL_RENDERER_ACCELERATED;
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, renderFlags);
    if (!renderer) {
        printf("error creating renderer");
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    SDL_Surface* surface = IMG_Load("dot.bmp");

    if (!surface) {
        printf("Error creating surface: %s\n", SDL_GetError());
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    SDL_FreeSurface(surface);
    if (!texture) {
        printf("error creating texture: %s\n", SDL_GetError());
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
    }

    SDL_Rect dest;

    dest.x = 0;
    dest.y = 0;

    SDL_QueryTexture(texture, NULL, NULL, &dest.w, &dest.h);

    Uint64 NOW = SDL_GetPerformanceCounter();
    Uint64 LAST = 0;
    double deltaTime = 0;

    while (true) {
        LAST = NOW;
        NOW = SDL_GetPerformanceCounter();
        deltaTime = (double)((NOW - LAST) / (double)SDL_GetPerformanceFrequency());

        SDL_RenderClear(renderer);

        dest.x += 50 * deltaTime;
        dest.y += 50 * deltaTime;

        SDL_RenderCopy(renderer, texture, NULL, &dest);

        SDL_RenderPresent(renderer);

        std::cout << "Delta Time: " << deltaTime << std::endl;
        std::cout << "FPS: " << 60.0 - deltaTime << std::endl;

        SDL_Delay(1000.0f / (60.0 - deltaTime));
    }

    return 0;
}

I used the suggestion from this post: How to calculate delta time with SDL?
I print out "delta time" and "FPS" to the console and, while the deltaTime is slightly different each time, the FPS is stable 60 (which is the same value that I use in SDL_Delay to calculate delay in ms).
But the test image is clearly moving not smoothly, it stutters and moves at inconsistent speed, and I can't understand why.
Please help me understand what I am doing wrong. I just can't understand it even after looking through many examples.


texts: Checking if point is inside the mesh via raycasting - where to cast rays?

texts:
I need to voxelize triangle meshes which involves testing if a point is located inside or outside the given mesh.
I have just implemented a basic algo based on raycasting and checking the number of ray-mesh intersections (by intersecting the ray with each triangle).

I select a position which lies outside the mesh: I add a small offset to the mesh's bounding box.
Then I cast a ray from the point being tested to the position calculated above.

1) How to find the position which definitely lies inside or outside the mesh?
What are good values for the 'offset' which is added to the mesh's bounds?
(Currently, I'm using offset = vec3(1,1,1).)

2) The method is very slow. For example, voxelizing "cow.ply" (17412 vertices, 5804 triangles) on a 128^3 grid takes almost 5 minutes on a 3 GHz CPU!
What is a good acceleration strategy? (I plan to add a uniform grid where each cell keeps indices to intersecting triangles.)


texts: How can I access a GameObject variable in mono script from editor script?

texts:
In the mono script :
using UnityEngine;

public class TileTest : MonoBehaviour
{
    public GameObject prefabPathOnTerrain;

Then in the editor script at the top :
private SerializedProperty prefabPathOnTerrain;

Then inside OnEnable()
private void OnEnable()
    {
        prefabPathOnTerrain = serializedObject.FindProperty("prefabPathOnTerrain");
    }

And then inside a method I want to use it as a GameObject :
And instead using CreatePrimitive to use Instantiate :
But doing :
GameObject go = Instantiate(prefabPathOnTerrain);

Will not work.
public void TerrainObjects(GameObject gameobject)
    {
        Terrain terrain = Terrain.activeTerrain;
        var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y));
        if (cube != null)
            return;

        if (cube == null)
        {
              GameObject go = Instantiate(prefabPathOnTerrain);

            //cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        cube.transform.localPosition = new Vector3(terrain.transform.localPosition.x + gameobject.transform.localPosition.x, 0, terrain.transform.localPosition.z + gameobject.transform.localPosition.y);
        cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);
        cube.transform.parent = GameObject.Find("Terrain Map").transform;

        cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y);
        cube.tag = "Terrain Map";
    }