texts: Design basics for Unity game: sport management type

texts:
I am planning the classes for my game; and I am having problems to figure out the best way to connect them.

In my game I do not have the classic structure of say a FPS; where you have the player class; with stats, and AI class with enemy AI. my game is more like a sport simulation manager type; so there are various entities:

The player; which take over a team (or play in a team)
The NPC: other players, managers, people that work in the club.
The team (club) itself; where either the player take control of it, so NPC will join it, or will play in it, so the team will have both player and NPCs.
Competitions: self explanatory; team participate in it.

I was thinking to make different base classes, one for team, NPC, player and competitions, but then I need to establish relations between them.

This look more like a DB with relation between tables, compared to a standard FPS game, where everything is strictly divided and you don't get class that "belong" to some other class.

I am using Unity BTW, so far I ahve the GameManager class; which initialize the main menu, the scene manager and UI manager.

Then I have 4 different class (player, NPC, competition and team), and this is where I am stuck. Should I create references to other classes, so when I instantiate for example a team class; then I will put in it a dataset to represent the NPC classes and the player class?

Or should they not know about each other at all, and all the interaction and logic should go in the gamemanager class?


texts: Game Design: Faction/Player circular relationship

texts:
For a Java game, say I have two classes:

Player, representing a player in the game.
Faction, representing a faction of players in the game.

When the game starts up, all factions are loaded into some collection and all players are loaded into some collection.

Collection<Player> players;
Collection<Faction> factions;

Say there are two variables:

Player player1;
Faction the_destroyers;

player1 is in the faction the_destroyers.

the_destroyers needs to reference player1, since player1 is in the_destroyers. At the same time, player1 needs to reference the_destroyers, for quick lookup (otherwise I would have to iterate through the collection of factions, which may be a very large collection).

Obviously, whichever variable is loaded first cannot reference the other, since the other has not yet been loaded.

Generally speaking, how do I get around this issue? Is there a simpler solution?


texts:
I have a coroutine that smoothly changes a variable in my UI, but when I pause the game, the coroutine pauses too. How can I fix that?

Code:

using UnityEngine;
using System.Collections;

public class HUDController : MonoBehaviour {
    public void PauseGame() {
        FreezeTime();
        StartCoroutine(ShowPauseMenu());
    }

    private void FreezeTime() {
        Time.timeScale = 0;
    }

    private IEnumerator ShowPauseMenu() {
        var pauseMenuCanvasGroup = GameObject.FindWithTag("PauseMenu").GetComponent<CanvasGroup>();
        var alphaValue = 1f;
        var velocity = 0f;
        var time = 0.15f;

        while (!Mathf.Approximately(pauseMenuCanvasGroup.alpha, alphaValue)) {
            pauseMenuCanvasGroup.alpha = Mathf.SmoothDamp(pauseMenuCanvasGroup.alpha, alphaValue, ref velocity, time);
            yield return null;
        }

        pauseMenuCanvasGroup.alpha = 1; // Since float is not accurate, manually set the alpha to 1
        pauseMenuCanvasGroup.interactable = true;
    }
}


texts: Unity Raycast works only once-Ignores NavMeshAgents

texts:
I'm new to unity and just trying to build a game.
I've been trying to use Raycast to detect if an enemy is next to the player and I can't seem to get the Physics.Raycast working properly.
Everything works fine in the scene mode and at the beginning of the start mode.But then it stops responding.
I checked threads with similar issues, but it seems I have all those covered(the most common issue is also addressed-the objects I am attempting to detect have rigidbodies and box colliders attached to them)
This is the script I'm working with.
public class hitPlayer : MonoBehaviour
{

    public GameObject player;
    public Transform m_transform;
    Animator playerAnimator;
    int layerMask;
    RaycastHit m_Hit;
    float maxDistance = 5f;

void Start()
{
    layerMask = 1 << 8;
    layerMask = ~layerMask;

    playerAnimator = player.GetComponent<Animator>();
}
public void onTouch()
{

    bool isHit = Physics.Raycast(m_transform.position, -m_transform.right, out m_Hit, maxDistance, layerMask);

    if (isHit)
    {
        playerAnimator.SetTrigger("leftHit");
    }
    else
    {
        playerAnimator.SetTrigger("rightHit");
    }

}
void OnDrawGizmos()
{

    bool isHit = Physics.Raycast(m_transform.position, -m_transform.right, out hit, maxDistance,layerMask);
    Debug.Log(isHit);
    if (isHit)
    {
        Gizmos.color = Color.red;
        Gizmos.DrawRay(m_transform.position, -m_transform.right * hit.distance);
    }
    else
    {
        Gizmos.color = Color.green;
        Gizmos.DrawRay(m_transform.position, -m_transform.right * maxDistance);
    }
}
}

Would highly appreciate your assistance in fixing this issue which is to get the raycast working right throughout the game. Thanks in advance.


texts: What component should hold the character movements in ecs and fsm?

texts:
In the below code, there's a FSM for CharacterState that will be handled also in CharacterSystem. The problem was, I don't know what component should hold movements data to process in CharacterState or CharacterSystem

public class CharacterState implements State<Entity> {
    STANDING,
    WALKING,
    RUNNING,
    IN_PAIN,
    DEAD
}

public enum Movements {
    STAND_STILL,
    MOVE_UP,
    MOVE_DOWN,
    MOVE_LEFT,
    MOVE_RIGHT,
    MOVE_UP_RIGHT,
    MOVE_UP_LEFT,
    MOVE_DOWN_RIGHT,
    MOVE_DOWN_LEFT;
}

CharacterComponent implements Component {
    Movements movement
}

MovementComponent implements Component {
    Movements movement
}

AnimationComponent implements Component {
    IntMap<Animation> map = new IntMap<Animation>();
}

animation.map.put(Movements.MOVE_UP.order, ASSET.CHAR_MOVE_UP);


texts: Image loaded from TGA texture isn't displayed correctly

texts:
I have a TGA texture containing this image:

The texture is 256x256.
So I'm trying to load it and map it to a cube:

#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>
#import <stdlib.h>
#import <stdio.h>
#import <assert.h>

GLuint width=640, height=480;
GLuint texture;
const char* const filename= "/Users/ramy/Documents/C/OpenGL/Test/Test/texture.tga";

void init()
{

    // Initialization

    glEnable(GL_DEPTH_TEST);
    glViewport(-500, -500, 1000, 1000);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, width/(float)height, 1, 1000);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);

    // Texture

    char bitmap[256][256][3];
    FILE* fp=fopen(filename, "r");
    assert(fp);
    assert(fread(bitmap, 3*sizeof(char), 256*256, fp) == 256*256);
    fclose(fp);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, bitmap);

}

void display()
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glColor3ub(255, 255, 255);

    glBegin(GL_QUADS);
    glVertex3f(0, 0, 0);
    glTexCoord2f(0.0, 0.0);

    glVertex3f(40, 0, 0);
    glTexCoord2f(0.0, 1.0);

    glVertex3f(40, 40, 0);
    glTexCoord2f(1.0, 1.0);

    glVertex3f(0, 40, 0);
    glTexCoord2f(1.0, 0.0);

    glEnd();

    glDisable(GL_TEXTURE_2D);
    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(width, height);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(display);
    init();
    glutMainLoop();
    return 0;
}

But this is what I get when the window loads:

So just half of the image is correctly displayed, and also with different colors.Then if I resize the window I get this:

Magically the image seems to fix itself, even if the colors are wrong.Why?


texts: How to draw 2D racing tracks using vector graphics?

texts:
See this game.

I am trying to build a similar one using Unity. However, I am not sure how to build the scene, specifically, the walls.  Unity 2D allows me to create Sprite, but what kind of sprite should I use? Or I am on the wrong direction?


texts: What's a simple way of sending game data between phones?

texts:
Using windows phones I need to send small amounts of data between phones in a turn based game. It's only a few bytes of data and does not need to be real time, something like in wordfeud or similar. There could be 2-4 players in one game and one players actions need to be sent to the other ones.

What would be the simplest way to manage this?

If it would be possible to easily extend to other platforms with monogame that would be nice but not a requirement right now (guess I'll cross that bridge when I come to it).

My initial hope was that this would be possible using some online service like scoreloop or openXlive that could handle all the online stuff (leaderboards, communications, social etc) but I haven't found one that can do it all.


texts:
I got the exercise to create a color map from a heightfield and given normals with alpha blending.
Therefore I have to blend 4 textures (deep-flat, deep-steep, high-flat, high-steep) depending on the height and slope.

First I'm calculating the 3 alpha values (lowest layer is fully opaque, does not need to be blended -> gras texture)

//slope:= 1.0f - normal.z at current pixel

￼void calcAlphas(float height, float slope, float& alpha1, float& alpha2, float& alpha3) {
   alpha1 = (1-height) * slope; //low-steep ->  dirt texture
   alpha2 = height;             //high-flat ->  pebbles texture
   alpha3 = height * slope;     //high-steep -> rock texture
}

After that I'm getting the color at the current pixel of all four textures and calculating the final color:

3 = 3 ∗3 +(1−3)∗(2 ∗2 + 1−2 ∗(1∗1 + 1−1 ∗0))

The result looks pretty good but it's very smooth. To compare my result I got a pattern how it should be.

Orignal:

My own color map:


texts: How can I make expanding bullet pattern shapes?

texts:
I want to make a series of expanding bullet patterns that form shapes such as squares, triangles, etc. An example of what I'm after can be seen in the following video where when the stars are collected the bullets explode in the shape of an expanding star:

https://youtu.be/7JGcuTWYdvU?t=2m41s


texts: What methods are there to discard points on one side of a surface but not the other?

texts:
Goal: Given a surface mesh (terrain), discard all points above a given elevation relative to the terrain. The terrain can change quite often due to tiling and LODs, so the point culling will need to be dynamic and have good performance. The camera in our scene is free floating, so no assumptions can be made in that respect.

Here is a side view of the problem:

My initial attempt was to draw the terrain, translated to the given elevation, only to the depth buffer. Then, when rendering the point cloud, discarding points that fail the depth test. There are a couple problems with this method though: I have to determine which side of the translated terrain the camera is on and, if above, flipping the depth test. Also, if the camera is looking at the terrain edge-on, points will be discarded that shouldn't be.

Any ideas are welcome, and let me know if I need to make clarifications regarding the task.


texts: how to guarantee the order of response in a service-oriented mmo server cluster

texts:
i'm working on a mmo server these days. it's a service-oriented architecture, every service is one process which processes a specific type of request, and i have inventory service, battle service, etc.
  when received a request from client, the request will be dispatched to some corresponding service, based on the request type.
  let's assume we received two requests from one client in the cluster-side request message queue, first request1 and then request2, then the two requests will be dispatched to service1 and service2. so request2 may be handled first and the client will receive response2 first and then response1, which will not be what the client expect.
  so i'm wondering how to guarantee that response will go back in the same order request come?


texts: How do I make NPC pathfinding look believable?

texts:
Is there an "academic" way to have NPC walking randomly on a map, but having a believable comportment ?

The obvious scenario is a armed guard who is walking around a basement to secure it. It's quite easy to set up a "believable" path.

What I'm looking for is a way to simulation a crowd in a small town, in fact. How can I make their move look like they aren't goalless robots.


texts:
I am in the process of creating an ability system with client prediction akin to Unreal Engine 4's Gameplay Ability System.
I found an edge case where the client's tags that are applied from effects become out of sync with the server.
The prediction method I use is the same as detailed here.
Here is a scenario that illustrates this:
The player has 2 abilities, an ability to unsheathe their weapon, and an ability to sheathe their weapon. Each ability requires a specific tag to activate. For the unsheathe ability, it is the "Sheathed" tag. For the sheathe ability, it is the "Unsheathed" tag.
There also exist two effects that apply these tags. The UnsheatheEffect applies the "Unsheathed" tag and the SheatheEffect applies the "Sheathed" tag.
The unsheathe ability lasts for 1 second and at the end applies the UnsheatheEffect and removes the SheatheEffect. The sheathe ability does the same thing but applies the SheatheEffect and removes the UnsheatheEffect.
In this scenario, the player has a static ping of 1 second.
0 seconds: The client activates unsheathe ability. Tags {"Sheathed"}
1 second: The server activates unsheathe ability.
1 second: The client finishes unsheathe ability. Tags {"Unsheathed"}
1 second: The client proceeds to activate sheathe ability. Tags {"Unsheathed"}
2 seconds: The server finishes unsheathe ability and starts the sheathe ability.
2 seconds: The client finishes the sheathe ability. Tags {"Sheathed"}
2 seconds: The client activates the unsheathe ability. Tags {"Sheathed"}
3 seconds: The client reconciles with what happened on the server as a result of the unsheathe ability. Tags {"Unsheathed", "Sheathed"}.
The issue is that the client has already gone through the process of removing tags after abilities, but they are soon added back because of the reconciliation with the server. I am really not sure what to do about this, because the client should be in sync with the server, but it ends up just messing up the whole system.


texts: How to achieve variable jump height in an elegant and natural way

texts:
I am making a platformer, with a methodical approach to player physics. This is how I do variable jump height:
if not btn() then
   g_fall *= 1.5
end

if (not is_grounded) then
   // fall gravity
   p.ay = g_fall
end

p is the player, p.ay is the acceleration.
g_fall is the constant falling gravity, which I apply to the player's acceleration if it's not on the ground. If the player isn't pressing the jump button I increase g_fall so player falls down quicker thus achieving variable jump height.
This is somewhat ok, but I have a spring where player can jump and it bounces player to the air.
hit.y = ispring.y - 2
hit.dx *= 0.2
hit.dy=-v0_jump * 1.5

hit is the player, v0_jump is the constant initial velocity I give to the player to jump.
When the player presses jump while on the spring, it jumps higher because the fall gravity is lower. But I want spring to give you the same jump height whether you press jump or not.
Now I could put a flag for spring jump and an if condition to test for spring jumps and adjust the fall gravity, but I am looking for a more elegant solution.
So what are some professional techniques for variable jump height that can solve my problem out of the box.


texts:
Other than using a wiki, what good (or purpose-built) tools allow for collaborative work on a game treatment?

I have a couple ideas I'd like to get fleshed-out and built, and have a small team who will work me on the project(s). How can we best iterate-over and define the game-play, graphical styles, etc?


texts:
I want to make a sprite blinking like this:

float alpha = .0f;

public void draw(SpriteBatch batch, float delta){
    alpha += delta;
    sprite.draw(batch, (float)Math.sin(alpha));
}

Well, it is blinking, but in a very irregular way. It should go from transparent to non-transparent to transparent and so on.
But with that code it is more like non-transparent to transparent - then it almost instantly skips back to non-transparent and goes back to non-transparent.

How can I optimize this?


texts: What could cause a pixel shader to paint outside the lines of the vertex shader output?

texts:
From what I understand, the pixels that a pixel shader operates on are specified implicitly by the SV_POSITION output (in DirectX) of the vertex shader. What then could cause a pixel shader to render in the middle of nowhere?

I used the new Visual Studio 2012 graphics debugger to visualize my vertex and pixel shader output. This is the output from a DrawIndexed() call that draws a cube:

The pink part is the rendered output of the pixel shader, which takes the cube on its left as its input.

The vertex shader code:

cbuffer Buf { float4x4 final; };

struct In
{
    float4 pos:POSITION;
    float3 norm:NORMAL;
    float2 texuv:TEXCOORD;
};

struct Out
{
    float4 col:COLOR;
    float2 tex:TEXCOORD;
    float4 pos:SV_POSITION;
};

Out main(In input)
{
    Out output;
    output.pos = mul(input.pos, final);
    output.col = float4(1.0f, 0.5f, 0.5f, 1.0f);
    output.tex = input.texuv;

    return output;
}

And the pixel shader:

struct In
{
    float4 col:COLOR;
    float2 tex:TEXCOORD;
    float4 pos:SV_POSITION;
};

float4 main(In input) : SV_TARGET
{
    return input.col;
}

The raster stage is the only thing between the vertex shader and the pixel shader, so my suspicion is that it's some raster stage settings. But the raster stage shouldn't change the shape of the vertex shader output so drastically, should it?


texts: How do I find artists to work on my game?

texts:
I ask "how" rather than "where" because there are undoubtedly lots of artists that are just plain lousy or unreliable.

Let's assume both paying and non-paying (mods, free games/open-source) positions.


texts: Spawning random items to drop from the top of the screen

texts:
I'm wondering how to make specific random objects drop. In my case, from the top of the screen.
I have 16 objects, named recycle_items_0 through recycle_items_15.
IEnumerator CreateRoutine()
{
    while (true)
    {
        yield return new WaitForSeconds(3);
        CreateItems0();
    }
}

private void CreateItems0()
{
   Vector3 pos = Camera.main.ViewportToWorldPoint(new Vector3(UnityEngine.Random.Range(0.0f,1.0f),1.1f,0));
   pos.z = 0.0f;
   Instantiate(recycle_items_0, pos, Quaternion.identity);
}


texts: XNA Sprite mouse selection with layered/overlapping sprites

texts:
If I use mouse coordinates to select a sprite does XNA provide a built in way to return the top-most sprite on the screen at a coordinate?

I am trying to highlight the selected sprite, but when iterating through my sprites at the specific mouse location there can be multiple sprites found.  The way my game works any one of the sprites found is valid to be on top.


texts: IDXGISwapChain::ResizeBuffers - should I recreate the depth/stencil buffer too?

texts:
When I resize the buffers via IDXGISwapChain::ResizeBuffers(), it is required to release any references to views to the back buffer. That of course makes sense, because the back buffer texture is about to be changed.

But nothing mentions whether I should change the depth/stencil buffer at the same time. I'm guessing it's not a requirement because D3D can scale before outputting, but is it a good idea anyway?

Thank you


texts: How do I organize my game into multiple classes in C#?

texts:
I've made two simple 2D games while following tutorials for the XNA libraries, and I wanted to make something myself, with only the knowledge I gained from these tutorials.

This will be my first serious attempt at game development, as well as my first C#/XNA project. I migrated from Java a week ago. Now, both of the tutorials I've followed made the whole game using only one class. And while it's possible, it isn't organized enough for me, and I want most of the functions to be organized in separate classes. So, I started with Input so I can have an easy way of exiting the game during testing right away.

Here's the important bits, I think:

From my Game1.cs:

protected override void Update(GameTime gameTime)
{
    Input input = new Input();
    input.PollInput();

    // TODO: Add your update logic here

    base.Update(gameTime);
}

From my Input.cs:

namespace MyFirst2DGame
{
    class Input
    {
        Game1 game = new Game1();

        public void PollInput()
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                game.Exit();
        }
    }
}

However, when I run the project, the Back button on the XBox 360 controller does nothing. My question, is am I missing something? I have no idea how to do anything with multiple classes, as all of my Java projects were quite small and had need for only one class.


texts: Is it possible to rotate an image on an HTML5 canvas, without rotating the whole canvas?

texts:
So I basically want to rotate single sprites on the canvas without rotating the whole canvas, is that someway possible.

I also don't want to create a new canvas for each object I have.

Also, it would be interesting to know which solution is then the most performant.


texts:
Using Canvas with Surfaceview I had a run() method where I would essentially do the following:

onDraw();
update();

Where onDraw method would do the rendering and update would update all my game physics / logic etc...

Having switched to openGL ES (2.0) and therefore now using a glSurfaceview, I have the following:

onDrawFrame(){

//Rendering code here

}

Which I don't call myself as it gets called automatically (my rendering is set to continuous).

So where / how do I run my logic updates?


texts:
I'm writing an original (top-down) SimCity clone in Swift and attempting to use SpriteKit as the basis for the game. However, I am running into performance issues when rendering and animating the tile map which represents the city map.

I'm rendering a 44x44 tile map with each tile being 16x16 pixels. Tile animation could happen on any arbitrary tile and is implemented by having a separate image for each frame of the animation. The map is dynamic (naturally) since the player will draw on it and tiles can be animated (roads, etc). I have tried several implementations to render the map the screen and each has had its own performance issues.

What I've tried:

Each tile is an SKSpriteNode with its texture loaded from a texture atlas. Textures were swapped for tiles that were dirty (needed redraw). I disabled physics simulations and physics bodies on the nodes.

Pros:

Minimal draws (due to the Texture atlas)
Code wasn't very complex

Cons:

Redrawing the entire map destroyed performance
Swapping textures to animate was inefficient

Map was rendered using NSView, drawRect, etc.

Pros:

Drawing was relatively efficient
Dirty rectangle drawing was easy to implement

Cons

Not really suitable for animation (really bad performance)

My question is: What is the most efficient way of rendering/animating my tile map? Is there an optimization I can make to SpriteKit to speed this up? Or do I need to use something lower level (OpenGL/GLSL) to draw/animate the map efficiently?

Any help would be greatly appreciated!


texts:
I'm going to be writing a very simple renderer, mainly for learning purposes (using OpengGL).
I've been wondering about how to implement support for dynamic number of light sources.
Two solutions that come to my mind are:

Define an upper limit for each kid of light source (point, directional etc) and pass an array of lights in an uniform.
Write a shader for each of the light source type, iterate over each light in the scene and invoke it's appropriate shader, giving it as input the gBuffer with positions, normals and etc. This seems inefficient for me, as we will loop n times through the fragments in the framebuffer, where n is the number of lights.

Are there any more solutions?


texts: How to Generate Spritesheet from a 'problematic' animated Symbol in Flash Pro CS6?

texts:
In the new Flash Pro CS6 there is an option to generate spriteheet from a symbol. I used these tutorials:

http://www.adobe.com/devnet/flash/articles/using-sprite-sheet-generator.html

http://tv.adobe.com/watch/cs6-creative-cloud-feature-tour-for-web/generating-sprite-sheets-using-flash-professional-cs6/

And it works really well!

An artist I'm working with created a bunch of assets for a game. One of them is a walking person as seen from a top-down view.

You can find the .fla here:

https://docs.google.com/folder/d/0B3L2bumwc4onRGhLcGNId1p2Szg/edit
 (If this does not work let me know, it is the first time I used Google Drive to share files)

1 .When I press ctrl+enter I can see it is moving. When I look for the animation, I do not seem to find it. When I select to create a spritesheet, flash suggest creating a spritesheet with one frame in the base pose and no other (animation) frames.

What is causing this and how do I correct it?

2 .I want to convert it to a sprite sheet for 32 angles of movement. Is there any magical easy way to get this done? Is there a workaround without using Flash CS6 to do the same thing?


texts: Too Low Amount of Tris in Statistics Window, Only in the Tens (Unity)

texts:
I'm working on a mobile game, and for optimization it would be useful to see the correct amount of polygons rendered.
However in the Statistics window the amount of polygons displayed are suspiciously low, only 62. Getting the poly count this low would be quite an achievement.
I'm using the Universal Rendering Pipeline.
Would there be a way to fix this?


texts:
I'm a hobbyist programmer at best and I had an idea I wanted to test in Unity, I wanted to rotate the game world around 90 degrees, to this end I've been learning a tiny bit about quaternions, in this  simple test I have a empty game object at position 0,0,0 and 2 cubes placed so only one will be in the foreground at once (both children of the empty game object). I simply want to rotate the parent object on a mouse up  like so.

if (Input.GetMouseButtonUp(0)) {

        Quaternion newrot = Quaternion.Euler (0,90,0);
        transform.rotation = Quaternion.Slerp (transform.rotation,newrot,0.05f);

    }
}

The problem I am having is that this does not do the rotation in a single click and never reaches 90 degrees, it only ever tends towards 90 (for fun I decided to click for 2 minutes and only got up to 89.99999 ... well you get the picture).

Can someone tell me what I am doing wrong and if there is a better way of doing this?


texts: How can I calculate the U,V texture coordinates on a disk at infinity given only a view vector and a vector pointing to the disk's center?

texts:
I'm using an approach similar to Bruneton's paper on atmospheric scattering for rendering my sky and am trying to extend it to add a textured moon.

Long story short, the paper works by essentially inverting a screen pixel to a world-space vector, then effectively raytracing the sky. To draw the sun, the paper checks the dot product between the sun-vector and pixel view-vector, and gives a "yes hit" or "no not hit" 1 or 0 based on a step function and the angular size of the sun. All of these vectors are unit.

Similarly, I'm doing the same thing to determine if there's a hit on the moon, however unlike the sun, I also now need to determine a texture coordinate. At first I simply subtracted the view vector from the moon vector, normalized the result, then scaled it by the angle between the view and moon vectors. This gives me the correct world-space point, but I'm having a hard time converting this 3-D world space point to a U,V texture coordinate on the intersected moon-disk.

A graphic to illustrate my problem:

My question is this:
Given two unit vectors, how can I calculate a texture coordinate of a point formed by the angle between them?


texts:
My anti-aliasing is not working in MonoGame.  I'm not sure if I'm doing something wrong.  See the image below (rotating the screen -- coordinates are all overlapping/adjacent, so should blend them):

http://imgur.com/a/xIj7C

On the ctor of my Game, I have the following:

        Graphics = new GraphicsDeviceManager( this )
        {
            PreferredBackBufferHeight = 720,
            PreferredBackBufferWidth = 1280,
            PreferMultiSampling = true
        };

        Graphics.ApplyChanges();

Which, should enable Anti-Aliasing.  Further, I have:

                GraphicsDevice.RasterizerState = new RasterizerState()
                {
                    CullMode = CullMode.None,
                    MultiSampleAntiAlias = true,
                };
                TileMeshEffect.CurrentTechnique.Passes[0].Apply();
                GraphicsDevice.SetVertexBuffer( TileMeshVertexBuffers[Coordinate] );
                GraphicsDevice.DrawPrimitives( PrimitiveType.TriangleList, 0, TileMeshVertexBuffers[Coordinate].VertexCount / 3 );

Right as I'm rendering the Mesh, which should, I would think, do everything necessary.  I was able to confirm via debugger that both are set, and that furthermore, the number of passes was 4 (GraphicsDevice.PresentationParameters.MultiSampleCount).

Any clue what I'm doing wrong?


texts:
What is the current state-of-the-art to network real-time strategy games?

I seem to recall that a few years ago, some AAA titles only transmitted the player inputs (Starcraft 1, Age of Empires). Since this requires you to keep everything else totally deterministic, is this still a viable option? Synchronizing random number generators seems feasible, but what about subtle differences in FPU implementations etc..?

Or are strategy games using something closer to action-game networking, where individual entities are transmitted instead (with some form of prediction and (delta) compression)?

If so, how are volatile items like projectiles treated?

What about client/server versus peer-to-peer? I'm guessing that all this is strongly interrelated.

Thank you for your time!


texts: Array but with a name for every element (value)

texts:
Say I have 10 different types of grenades, I would like to create one variable, to allow me to set the number of grenades given from the inspector, I could create an array with 10 integers and set the number of grenades there, however it would be much easier for me if every element of the array (10 in total) had a name next to its value in the inspector so I could clearly see which grenade type am I assigning the value.

Is there any variable type or something that would allow me to do this? If so what is it? And how can I create what I want?

Thanks in advance!

If more information/ better explanation of some aspect is needed ask.


texts: Libnoise producing completely random noise

texts:
I am using libnoise in C++ taken and I have some problems with getting coherent noise. I mean, the noise produced now are completely random and it doesn't look like a noise.

Here's the image produced by my game.

I am dividing the map into several chunks, but I can't seem to find any problem doing that since libnoise supports tileable noise. The code can be found below.

Every chunk is 8x8 tiles large. Every tile is 64x64 pixels.

This is the code for generating a chunk

 Chunk *World::loadChunk(sf::Vector2i pPosition)
 {
     sf::Vector2i chunkPos = pPosition;
     pPosition.x *= mChunkTileSize.x;
     pPosition.y *= mChunkTileSize.y;
     sf::FloatRect bounds(static_cast<sf::Vector2f>(pPosition), sf::Vector2f(static_cast<float>(mChunkTileSize.x), static_cast<float>(mChunkTileSize.y)));

     utils::NoiseMap heightMap;
     utils::NoiseMapBuilderPlane heightMapBuilder;
     heightMapBuilder.SetSourceModule(mNoiseModule);
     heightMapBuilder.SetDestNoiseMap(heightMap);
     heightMapBuilder.SetDestSize(mChunkTileSize.x, mChunkTileSize.y);
     heightMapBuilder.SetBounds(bounds.left, bounds.left + bounds.width - 1, bounds.top, bounds.top + bounds.height - 1);
     heightMapBuilder.Build();

     Chunk *chunk = new Chunk(this);
     chunk->setPosition(chunkPos);
     chunk->buildChunk(&heightMap);
     chunk->setTexture(&mTileset);
     mChunks.push_back(chunk);
     return chunk;
 }

This is the code for building the chunk

void Chunk::buildChunk(utils::NoiseMap *pHeightMap)
{
    // Resize the tiles space
    mTiles.resize(pHeightMap->GetWidth());
    for (int x = 0; x < mTiles.size(); x++)
    {
        mTiles[x].resize(pHeightMap->GetHeight());
    }

    // Set vertices type and size
    mVertices.setPrimitiveType(sf::Quads);
    mVertices.resize(pHeightMap->GetWidth() * pHeightMap->GetWidth() * 4);

    // Get the offset position of all tiles position
    sf::Vector2i tileSize = mWorld->getTileSize();
    sf::Vector2i chunkSize = mWorld->getChunkSize();
    sf::Vector2f offsetPositon = sf::Vector2f(mPosition);
    offsetPositon.x *= chunkSize.x;
    offsetPositon.y *= chunkSize.y;

    // Build tiles
    for (int x = 0; x < mTiles.size(); x++)
    {
        for (int y = 0; y < mTiles[x].size(); y++)
        {
            // Sometimes libnoise can return a value over 1.0, better be sure to cap the top and bottom..
            float heightValue = pHeightMap->GetValue(x, y);
            if (heightValue > 1.f) heightValue = 1.f;
            if (heightValue < -1.f) heightValue = -1.f;

            // Instantiate a new Tile object with the noise value, this doesn't do anything yet..
            mTiles[x][y] = new Tile(this, pHeightMap->GetValue(x, y));

            // Get a pointer to the current tile's quad
            sf::Vertex *quad = &mVertices[(y + x * pHeightMap->GetWidth()) * 4];

            quad[0].position = sf::Vector2f(offsetPositon.x + x * tileSize.x, offsetPositon.y + y * tileSize.y);
            quad[1].position = sf::Vector2f(offsetPositon.x + (x + 1) * tileSize.x, offsetPositon.y + y * tileSize.y);
            quad[2].position = sf::Vector2f(offsetPositon.x + (x + 1) * tileSize.x, offsetPositon.y + (y + 1) * tileSize.y);
            quad[3].position = sf::Vector2f(offsetPositon.x + x * tileSize.x, offsetPositon.y + (y + 1) * tileSize.y);

            // find out which type of tile to render, atm only air or stone
            TileStop *tilestop = mWorld->getTileStopAt(heightValue);
            sf::Vector2i texturePos = tilestop->getTexturePosition();

            // define its 4 texture coordinates
            quad[0].texCoords = sf::Vector2f(texturePos.x, texturePos.y);
            quad[1].texCoords = sf::Vector2f(texturePos.x + 64, texturePos.y);
            quad[2].texCoords = sf::Vector2f(texturePos.x + 64, texturePos.y + 64);
            quad[3].texCoords = sf::Vector2f(texturePos.x, texturePos.y + 64);
        }
    }
}


texts:
So me and a couple of people are building a game with Unity, and I wanted to figure out how to keep the score in sync with all of the clients. After a lot of looking around on both the internet and the Unity API Docs, I found these things called NetworkMessages, However I do not know exactly what they do, or how to use/send/receive them. My first guess for what they were was, a simple way I could send any kind of data to all clients with them.

Please tell me if i'm right, if not what are they, and how would I go about using them to maybe keep the game score in sync with all of our clients.

Thanks!


texts: Steps to take before trying to implement screen space ambient occlusion

texts:
I very recently started learning modern OpenGL. I have implemented a wavefront file loader and a basic ADS shading model. At some point I'd like to implement screen space ambient occlusion. I tried reading on the technique and I understand the concept, but I have trouble understanding the details (i.e. extracting the depth information and reconstructing the positions in space etc.).

Thus the question is, what techniques should I learn/practice before trying to implement the SSAO?


texts: Timestep schemes for physics simulations

texts:
The operations used for stepping a physics simulation are most commonly:

Integrate velocity and position
Collision detection and resolution
Contact resolution (in advanced cases)

A while ago I came across this paper from Stanford that proposed an alternative scheme, which is as follows:

Collision detection and resolution
Integrate velocity
Contact resolution
Integrate position

It's intriguing because it allows for robust solutions to the stacking problem.  So it got me wondering...

What, if any, alternative schemes are available, either simple or complex?  What are their benefits, drawbacks, and performance considerations?


texts:
I'm about to make a 3D Rubik's cube based game in Flash AS3 and Away3d.

I don't really know how to manage the 2D arrays of the Rubik's cube.

For example, how do I rotate the corresponding arrays if I rotate a side, or just rotate a middle part?

In this stage I also don't know how to rotate those smaller cube parts all together if a side is rotating. First I was thinking of "groups" ( like in sketchup or 3ds max, blender), but that would be tricky, because the group components would change every time.

So I was thinking of just rotating each individual piece along a global axis. However, I just know the Away3d functions to rotate the cube of his local X , Y or Z axis, but how to rotate in global axis?

Does anyone know of a algorithm for doing these types of rotations?


texts: How do I calculate consistent frame timings at 60fps?

texts:
I'm writing an HTML canvas game that uses requestAnimationFrame and therefore runs at 60fps, although this is more of a question about failing arithmetic than about JavaScript.

If I measure the time since the last frame in order to update my sprite positions correctly, I get a slight jitter in the movements. This is because the times are accurate to the millisecond, and 1/60s does not neatly fall on millisecond boundaries.

What I end up seeing are timings like this:

16, 17, 17, 16, 17, 17, 16, 17, 17, 16

(In reality I get more 16s than 17s because of time spent outside of the timed region of code, but you get the idea).

This timing difference means that on each frame that updates on a perfect 1/60 monitor refresh rate, I advance my sprites at an imperfect rate.

My solution is to lie about my timing. I'd like to round my timings to the nearest multiple of 1/60s, expressed in ms.

E.g. If I get around 16ms timings, I'd like to report 16. If I get around about 33ms timings (1 dropped frame), I'd like to report 33.

Is there a magical formula that will do this?


texts:
I am working on a 2D action platformer in Python, though my question is a general one about creating snakelike objects which move in a variety of patterns.

I have noticed this kind of object in many 2D games. For example, this boss in Contra has snakelike arms.

And this enemy from Super Metroid clearly seems to be composed of multiple segments.

I want to create snakelike objects in my game, though I don't know where to begin or what I may need to add to my physics engine to support them.

So far, all my enemies and hazards consist of single sprites and are programmed using simple attributes like velocity, acceleration, parametric curves, etc.

Maybe I need to create a class for the segments, designate one segment instance as the leader, and update the positions of the  other segments based on the position of the segment in front of it. But how do I program different patterns of movement? Do I need to learn about so-called joints and implement them between the segments? I currently don't have them in my engine.

I know I could easily create a segmented object where each non-leader segment is moved to the previous position of the segment in front of it (like in classic Snake, described here), but I want more complex patterns than this. Sometimes I may want the object to be flailing from an anchored point, and other times I may want it to be following some pattern across the screen.

I really don't know where to begin in trying to create this kind of object and would greatly appreciate any advice.

How do you implement snakelike objects with a variety of movement patterns?

(Given the ubiquity of this kind of object in games, I was surprised that I couldn't easily find much about it online. I think a detailed write-up on it would be cool.)


texts: I am trying to simulate a camera which is always at same distance behind my player, my plan is, to transform the projection matrix correctly with glPush/PopMatrix, as i do it with the modelview matrix. While it's no problem, to rotate the view constantly, it doesn't work to save the current matrix with glPush/PopMatrix. In another thread, I've read that the size projection stack is very limited, one or two at most. If this is true and the 'stack' doesn't  offer the possibility to save the current matrix, is there another way to get what i want? Or is my idea a non-practicable approach at all? Is there no alternative to use gluLookAt()? Or is it the right solution to transform the  modelview matrix and save the position of the player figure?


texts: How can i get a value from object in tmx file in Cocos2d x 3.x?

texts:
I want to set my sprite in x coordinate based on an object in TMX map file,
this is my code:

tileMap = cocos2d::TMXTiledMap::create("ground.tmx");
ground = tileMap->layerNamed("ground");
this->addChild(tileMap);

TMXObjectGroup *objects = tileMap->objectGroupNamed("objects");
Dictionary *sign = (Dictionary*)objects->objectNamed("sign");

How can i get a value of object in tmx file in Cocos2d x ?


texts:
I posted this on stackoverflow but was advised to post here (here is a link to the stackoverflow question). I'm hoping for constructive feedback on its plausibility.

Update on progress: It looks like there are ways to stuff files back onto the console (horizon, modio, xplorer360, etc) and they do require some form of signing.

As of now, though, I've had no luck. I was hoping I could get away with just placing the ".esp" into the directory containing marketplace downloads for Skyrim, along with the signed ".bsa" file (basically a zipped up file containing any extra content the .esp will need to refer that doesn't exist in the basic game).

This doesn't work, at least not in the ways I've tried, so next I'm going to try install the entire game to my flash drive (if possible) and attempt to traverse through the game's directory (this is probably unlikely).

If anyone else has suggestions or luck or wants more detail on my failures comment/answer away.

Here is the question:

  I'm thinking about buying the PC version of Skyrim to get the Creation
  Kit (I already own a copy for the Xbox). I have read the faq and
  scoured plenty of forums to see if there was some way to mod Skyrim
  for a console (Xbox 360, in particular), but they are generally coming
  up negative.

  I realize the CreationKit is on the PC, but I was wondering if there
  was a way to set up the '.esp' (hopefully I'm interpreting this
  correctly) files to be placed on the Xbox 360 file system in a similar
  manner to how game add-ons are downloaded from the Xbox Live
  Marketplace.

  I believe it is possible to transfer saves between the console and the
  PC (e.g. google: 'skyrim mod xbox360'), but these are referencing
  items that already exist in the game (e.g. a console command for
  maximum carry weight does not require reference to new animations or
  models).

  It would probably be easier if one could navigate through the xbox's
  file system to see where the games' files are placed, but with the
  current setup, the file system is abstracted away.

  Any help or insight on the matter would be much appreciated. I would
  love to work on a project that would make it possible to let console
  gamers experience and enjoy all the great mods available to the PC
  community.


texts: What is a good "easily" moddable and scriptable 3D game?

texts:
I've made a fair number of 2D games (and actually completed/released a few of them). I'm hesitant to move into the 3D realm, because of the order of magnitude (everything takes ~10x more work).

To get started, I was thinking about picking something and modding it. What's a good, "easily" moddable game? By easily, I really mean:

Most or all of the content can be changed via tools (not code)
Tools are included, and mature (don't crash much, etc.)
The game is free or cheap
The game is scriptable (scripting language or SDK)

I'm not really particular about a target language, although I lean towards something more like C# than JavaScript.

If this is not a "good" question, we can make it a list and community wiki it. I really want to know options to get started in the 3D modding realm.


texts: How can I get my objects to move at the same speed regardless of frame rate?

texts:
I tried using the methods on lazyfoo's site for frame rate independence. One problem I'm having though is that my game is running at different speeds on different computers. The differences are drastic. For example, on a Core 2 Duo 2.4 ghz 2gb ram PC, the ball will move extremely fast, but the paddle moves slowly. On an Intel Centrino laptop running Win7 w/plenty of ram, the ball moves slowly, but the paddle moves fast. On older computers like a Pentium 4 2.4 ghz, 768 ram computer, the ball moves realllllllllyyyyyyy sllllooowwww. Yes, that slow.

What might be some reasons this is happening, and how can I fix it? I can only assume that the code I wrote that deals with frame rate independence is wrong. Here are the relevant parts of the code. (btw, it's a breakout clone).

Code to move the ball

bool Ball::MoveBall( Uint32 deltaTicks )
{
    // X-COORDINATE
    xOffset += cos( radians ) * ( ballVelocity / 1000.f ) * flipx;
    ballPosition.x = (Sint16)xOffset;

        .......

    // Y-COORDINATE
    yOffset += sin( radians ) * ( ballVelocity / 1000.f ) * flipy;
    ballPosition.y = (Sint16)yOffset;

    .....
}

Code to move the paddle

void Paddle::Move( Uint32 deltaTicks )
{
    xOffset += xVel * ( deltaTicks / 1000.f );
    paddlePosition.x = (Sint16)xOffset;
}

Main loop

    while ( SDL_PollEvent( &gEvent ) )
    {
        handle.PaddleInput( &gEvent, stick );

        if ( gEvent.type == SDL_QUIT || gEvent.key.keysym.sym == SDLK_ESCAPE )
            quit = true;
    }
    stick.Move( time.GetTicks() );

    if ( ball.MoveBall( time.GetTicks() ) )
        wallSound.Play();

    if ( ball.CheckPaddleCollision( stick ) )
        paddleSound.Play();

    if ( ball.CheckBrickCollision( brickmap ) )
        brickSound.Play();

    if ( ball.IsBallDead() ) {
        ball.ResetBallPosition();
        stick.ResetPaddlePosition();
        stick.SetPaddleState( Paddle::RESET );
        launched = false;
        draw.GameObjects( lvl, brickmap, stick, ball );
    }

    draw.GameObjects( lvl, brickmap, stick, ball );
    time.Start();
    draw.Refresh();


texts: How would the game engine used impact monetization of games?

texts:
Does the game engine you use affect monetization of indie games? Of course, targeting difficult platforms is one of the issues.

Besides that, how would the game engine used impact monetization of games, assuming cases where the developers are going through a portal, and handling the online distribution, themselves? As an example, if I make a game in DarkBASIC, will it be harder to sell it than one made with Popcaps Framework or ClanLib etc.?


texts: Offloading processing to a remote server in a game engine?

texts:
What kinds of processes can you offload to a remote server in a game engine?

I'm thinking of making a real time multiplayer RTS, like Starcraft for example.

I was trying to offload as many processes as possible onto a remote server to:

1) Practice the techniques involved in order to offer a responsive gaming experience
     while taking advantage of the latest cloud processing techniques.

2) To make an engine that's the most platform independent possible.

I've already thought of a couple of things that could be processed remotely:

AI (Path finding)
Volumetric particle effects (Smoke after an explosion)
Loading between levels?

I'm also most curious about the following things being possible:

Rendering
Physics

If anybody has any knowledge to share about this subject I'd very much appreciate some guidance.


texts: How do I check on non-transparent pixels in a bitmapdata?

texts:
I'm still working on my window cleaning game from one of my previous questions

I marked a contribution as my answer, but after all this time I can't get it to work and I have to many questions about this so I decided to ask some more about it. As a sequel on my mentioned previous question, my question to you is:

How can I check whether or not a bitmapData contains non transparent pixels?
Subquestion: Is this possible when the masked image is a movieclip? Shouldn't I use graphics instead?

Information
I have: A dirtywindow movieclip on the bottom layer and a clean window movieclip on layer 2(mc1) on the layer above.

To hide the top layer(the dirty window) I assign a mask to it.

Code

// this creates a mask that hides the movieclip on top
var mask_mc:MovieClip = new MovieClip();
addChild(mask_mc)

//assign the mask to the movieclip it should 'cover'
mc1.mask = mask_mc;

With a brush(cursor) the player wipes of the dirt ( actualy setting the fill from the mask to transparent so the clean window appears)

//add event listeners for the 'brush'
brush_mc.addEventListener(MouseEvent.MOUSE_DOWN,brushDown);
brush_mc.addEventListener(MouseEvent.MOUSE_UP,brushUp);

//function to drag the brush over the mask
function brushDown(dragging:MouseEvent):void{
    dragging.currentTarget.startDrag();
    MovieClip(dragging.currentTarget).addEventListener(Event.ENTER_FRAME,erase) ;
    mask_mc.graphics.moveTo(brush_mc.x,brush_mc.y);
}

//function to stop dragging the brush over the mask
function brushUp(dragging:MouseEvent):void{
    dragging.currentTarget.stopDrag();
    MovieClip(dragging.currentTarget).removeEventListener(Event.ENTER_FRAME,erase);
}

//fill the mask with transparant pixels so the movieclip turns visible
function erase(e:Event):void{
    with(mask_mc.graphics){
        beginFill(0x000000);
        drawRect(brush_mc.x,brush_mc.y,brush_mc.width,brush_mc.height);
        endFill();
    }

}


texts: How do I correctly use SDL_RegisterEvent to create SDL_UserEvents?

texts:
I've been looking to use SDL's own event messaging system to pass events around to different parts of my game, since it supports user events.

However, the documentation isn't very clear. Here is the code snippet it gives:

Uint32 myEventType = SDL_RegisterEvents(1);
if (myEventType != ((Uint32)-1)) {
    SDL_Event event;
    SDL_memset(&event, 0, sizeof(event)); /* or SDL_zero(event) */
    event.type = myEventType;
    event.user.code = my_event_code;
    event.user.data1 = significant_data;
    event.user.data2 = 0;
    SDL_PushEvent(&event);
}

My questions:

Does every type returned by SDL_RegisterEvents get read as SDL_UserEvent? If so, why even bother registering more than one event when you can use the event.user.code field to differentiate between types?
Do I need to call SDL_RegisterEvents each time I want to push my own event onto the event queue? Does this mean once the event I queue up is read, it trashes the type given to me by SDL_RegisterEvent and recycles it for another call?

The wiki is fairly vague, and there is next to nothing out there about using the SDL_UserEvent event type, so I am not entirely sure how to take advantage of SDLs built-in event handling system.


texts:
So the way that I am doing the movement for my game is that you can left click a unit (which is just a rectangle object), and then it is selected. While it is selected, you can right click and that will be the unit's destination.

This is the process input method:

    public void ProcessInput(Vector2 mouseLoc)
    {
        // SO, I have to take this mouse location, which is the location on the screen
        // And convert it to a "world" coordinate

        Vector2 distance = new Vector2(mouseLoc.X - position.X, mouseLoc.Y - position.Y);

        if (distance.Length() < speed)
        {
            position = mouseLoc;
            isMoving = false;
        }
        else
        {
            distance.Normalize();
            Vector2 toMove = new Vector2((int)(distance.X * speed), (int)(distance.Y * speed));
            position += toMove;
            bounds = new BoundingSphere(new Vector3(position, 0), radius);
        }
    }

I have a basic Wall class that is essentially just another rectangle object but with different properties like textures and what not.

This is my check collision method with the wall:

    public Boolean checkCollision(Wall wall)
    {
        if (wall.Bounds.Intersects(this.bounds))
        {
            Vector2 direction = new Vector2((position.X - destination.X) * -1,
            (position.Y - destination.Y) * -1);
            direction.Normalize();
            position += direction * 5;
            destination = position;
            return true;
        }
        return false;
    }

The problem is that the unit just kinda gets stuck in the wall when it hits it. I'm wondering what is the best way to fix this problem. I know that I have to move the unit out of that spot, but I'm not sure how to.

Any thoughts on how to handle this are appreciated.


texts: How to properly do weapon cool-down reload timer in multi-player laggy environment?

texts:
I want to handle weapon cool-down timers in a fair and predictable way on both client on server.

Situation:

Multiple clients connected to server, which is doing hit detection / physics
Clients have different latency for their connections to server ranging from 50ms to 500ms.
They want to shoot weapons with fairly long reload/cool-down times (assume exactly 10 seconds) It is important that they get to shoot these weapons close to the cool-down time, as if some clients manage to shoot sooner than others (either because they are "early" or the others are "late") they gain a significant advantage.
I need to show time
remaining for reload on player's screen
Clients can have clocks which are flat-out wrong (bad timezones, etc.)

What I'm currently doing to deal with latency:

Client collects server side state in a history, tagged with server timestamps
Client assesses his time difference with server time:

behindServerTimeNs = (behindServerTimeNs + (System.nanoTime() - receivedState.getServerTimeNs())) / 2

Client renders all state received from server 200 ms behind from his current time, adjusted by what he believes his time difference with server time is (whether due to wrong clocks, or lag). If he has server states on both sides of that calculated time, he (mostly LERP) interpolates between them, if not then he (LERP) extrapolates.
No other client-side prediction of movement, e.g., to make his vehicle seem more responsive is done so far, but maybe will be added later

So how do I properly add weapon reload timers?

My first idea would be for the server to send each player the time when his reload will be done with each world state update, the client then adjusts it for the clock difference and thus can estimate when the reload will be finished in client-time (perhaps considering also for latency that the shoot message from client to server will take as well?), and if the user mashes the "shoot" button after (or perhaps even slightly before?) that time, send the shoot event.

The server would get the shoot event and consider the time shot was made as the server time when it was received. It would then discard it if it is nowhere near reload time, execute it immediately if it is past reload time, and hold it for a few physics cycles until reload is done in case if it was received a bit early.

It does all seem a bit convoluted, and I'm wondering whether it will work (e.g., whether it won't be the case that players with lower ping get better reload rates), and whether there are more elegant solutions to this problem.


texts:
I have a top-down game you can scroll through placeable tiles I have some NPCs that do nothing at the moment I want them to freely move around without going through wall tiles etc.

For the freely moving I have code and it works fine but they walk through walls:

if(new Random().nextInt(4) == 0){
   x+=1;
}
if(new Random().nextInt(4) == 1){
   x-=1;
}
if(new Random().nextInt(4) == 2){
   y+=1;
}
if(new Random().nextInt(4) == 3){
   y-=1;
}

How can I make it so they don't walk through walls?

All the solid tiles are stored in an arraylist

public static ArrayList<block> s = new ArrayList<block>();

and then have the for loops for them and each block has its own rectangle around it.


texts: How to flip sprites with different dimensions horizontally?

texts:
I am trying to make an animation on HTML5 Canvas with this texture atlas, which was packed by TexturePacker:

and it works good when the Character is facing right. I try to flip it horizontally, but it gets wrong position:

Here is my current code, each frame has a offset value to fix position:

<canvas id="c" width="200" height="100" style="background: #000"></canvas>

var metaData = [
    {x:0,y:0,w:35,h:38,offsetX:3,offsetY:9},
    {x:37,y:0,w:31,h:37,offsetX:6,offsetY:10},
    {x:70,y:0,w:65,h:47,offsetX:0,offsetY:1},
    {x:137,y:0,w:65,h:47,offsetX:0,offsetY:1},
    {x:204,y:0,w:61,h:46,offsetX:1,offsetY:1},
    {x:267,y:0,w:42,h:46,offsetX:1,offsetY:1},
    {x:311,y:0,w:43,h:44,offsetX:1,offsetY:3},
    {x:356,y:0,w:38,h:37,offsetX:6,offsetY:10},
    {x:396,y:0,w:35,h:34,offsetX:6,offsetY:13},
    {x:433,y:0,w:33,h:37,offsetX:7,offsetY:10},
    {x:468,y:0,w:36,h:40,offsetX:5,offsetY:7},
    {x:506,y:0,w:34,h:39,offsetX:6,offsetY:8}
],
dx = 0, //position x
dy = 0, //position y
index = 0; //frame index

(function draw() {
    context2D.clearRect(0,0,c.width,c.height);

    var cur = metaData[index];

    if(facingRight) {
        context2D.drawImage(
            img,
            cur.x, cur.y,
            cur.w, cur.h,
            dx + cur.offsetX, dy + cur.offsetY,
            cur.w, cur.h
        );
    } else {
        context2D.save();
        context2D.scale(-1,1);
        context2D.drawImage(
            img,
            cur.x, cur.y,
            cur.w, cur.h,
            -dx - cur.offsetX - cur.w, dy + cur.offsetY,
            cur.w, cur.h
        );
        context2D.restore();
    }

    index = ++index % metaData.length;

    setTimeout(draw,100);
})();

I use scale(-1,1) to flip sprite, but I have no idea how to keep it at the same postion like facing right. Should I have to fix the offset value?

Please, any help will be appreciated :)


texts: Approaches on detecting if a car should steer left or right considering a next direction

texts:
I'm developing the A.I. of my racing game, and I'm having an unforeseen problem. I manage to get the bot to drive by itself by accelerating in the direction of an angle that is returned using the atan2 trig function considering the position of previously-defined waypoints on the track data structure. Here's the code for ai.py:

import math
import pygame

class Bot:

    def __init__(self, player, track):
        self.player = player
        self.track = track
        self.current_waypoint = 1
        self.player.states[0] = True
        self.track.choose_waypoint_path()
        self.number_of_waypoints = len(self.track.waypoint_positions.keys())
        self.get_waypoint_angle()

    def get_waypoint_angle(self):
        self.dx = self.track.waypoint_positions[self.current_waypoint][0] - self.player.car.pos[0]
        self.dy = self.track.waypoint_positions[self.current_waypoint][1] - self.player.car.pos[1]
        self.ratio = math.atan2(self.dy, self.dx)
        self.angle = -self.ratio * (180/math.pi)

    def think(self):
        if pygame.Rect(self.player.car.pos, self.player.car.dimensions).collidepoint(
            self.track.waypoint_positions[self.current_waypoint][0],
            self.track.waypoint_positions[self.current_waypoint][1]
        ):
            self.track.choose_waypoint_path()
            self.number_of_waypoints = len(self.track.waypoint_positions.keys())
            if self.current_waypoint == self.number_of_waypoints:
                self.current_waypoint = 0
            self.current_waypoint += 1
        self.get_waypoint_angle()
        self.player.car.angle = self.angle
        self.player.car.rotate()
        self.player.move()

The thing is, when I set the car angle based on the return of the atan2 function, self.player.car.angle = self.angle, the car rotates/turns in an extremely unrealistic fashion. It works, but it means that I have to gradually steer the car, and then I face this problem. I don't know when to steer left or right, because the angle can be negative. If I do this, for example:

        if self.player.car.angle > self.new_angle:
            self.player.car.angle -= self.player.car.steering_speed
        else:
            self.player.car.angle += self.player.car.steering_speed

The bot drives to the next waypoint destination by weirdly driving in circles.

So, I know the direction in which the bot should drive, but based on its previous angle, I don't know whether it should steer left or right to reach that direction.


texts: How does this snippet of code create a ray direction vector?

texts:
In the Minecraft source code, this code is used to create a direction vector for a ray from pitch and yaw:'

float f1 = MathHelper.cos(-rotationYaw * 0.01745329F - 3.141593F);
float f3 = MathHelper.sin(-rotationYaw * 0.01745329F - 3.141593F);
float f5 = -MathHelper.cos(-rotationPitch * 0.01745329F);
float f7 = MathHelper.sin(-rotationPitch * 0.01745329F);
return Vec3D.createVector(f3 * f5, f7, f1 * f5);

I was wondering how it worked, and what is the constant 0.01745329F?


texts:
I'm doing a HTC Vive VR game with Unity.

I have 3 objects, and I want to trigger different events when the player pick up different objects.

Since I set the rigidbody to the controller and don't want these events to be triggered by moving the objects by accident, I need to set up two rules: 1) the object is out of the invisible bounding box it is in; 2) object is being hold by he player with the trigger.

How should I script that?


texts: Finding the closest face normal from a given point in space efficiently

texts:
I have a large model (roughly 400k faces) and a large number of points on this model (roughly 2000) and I need to calculate a normal per point based on the closest face on the model. Is there a faster way that isn't O(n*m) where n is the number of points and m is the number of faces (e.g., raycasting or iterating through every face)?

I'm using THREE.js and the target hardware is a Toshiba tablet with Intel integrated graphics so I don't have a lot of power to work with. Currently if I compute this on load it takes about 10+ minutes.

I've been given the requirement that there shouldn't be any model specific information precomputed for each point so that we can use the points on a different model without recomputing everything and then have multiple datasets of point => normal mappings. This is currently what we are doing and it works but doesn't scale well to our needs.


texts: Assistive Machine Learning for Scene Creation

texts:
A few years ago, I have seen a talk about assistive ML tools in game development. I think was from
Ubisoft La Forge, but could be wrong.
In the video it was demonstrated, how an „AI“ understood the relationship of objects in a room and it was possible to give it simple commands like „clean the room“ and everything was put in its place, like books in the shelf, chess pieces on the board and so on. But it was also possible to ask to make the room look used by a child to change the scene accordingly.
The problem is, I can‘t find the video anymore and neither do I remember the name of the tool or the creator. Any idea how it was called and what‘s the state of it?


texts: Best way to generate pieces in match-3 games, and then tracking them?

texts:
I've been working on a match-3 style game in Actionscript using Flixel, and so far, I've been able to build the core mechanics of the game, including board generation, piece generation, piece swapping and movement, and checking algorithms.

However, I am now running into issues with clearing out pieces and letting the above pieces fall down and generating new pieces.

The reason I'm running into these issues is that when all of the pieces are generated, the pertinent values (position, sprite ID, and sprite object) are pushed into an array that helps me track everything, all the time. When pieces are moved, I swap the values of the corresponding arrays and life goes on.

And that array is the core of my problem: if a row in the middle of the board clears out, ideally, all of the pieces above the cleared pieces should fall down to take their place and new pieces are generated at the top and also fall into place. Except if I try to do that now, all the pieces can fall down, but then I'd have to bump all of their values into the right arrays (oh god my head) and then generate new pieces and fit THOSE into the correct place in the array.

Am I overthinking this? Or is there a far better way to track these pieces?

Thanks guys!


texts: Experiencing Multiple Issues with Code Possibly Caused By Outdated Tutorial

texts:
As somebody very new to Unity5, I was learning the first steps through a video tutorial and finally got to the coding part of everything.  However, subsequent to completion of learning coding, it seems to be having difficulties with the code I typed.  Before posting here, I checked for any differences that might be the cause, but after a few look-overs, I couldn't find the problem.  I've been having this problem with the Personal Edition of Unity.  I've been following along with the DigitalTutors tutorial, "Exploring the 2D Features in Unity".  Unfortunately, I had some errors, such as Unity telling me that 'rigidbody2D' was obsolete.  Following changing it to 'Rigidbody2D', I got the following errors which stumps me.

I think it also might be worth mentioning that I took some mild liberties with the assets.  Some of the assets used in the original tutorial were replaced with some of my own I created.  I gave the animations the same names and coded it all the same, but there were definitely a few cosmetic changes I made.

Below, I've done my best to format the errors.

Assets/Scripts/MovementController.cs(23,73): error CS0120: An object reference is required to access non-static memberUnityEngine.Rigidbody2D.velocity`
Assets/Scripts/MovementController.cs(23,84): error CS1502: The best overloaded method match forUnityEngine.Vector2.Vector2(float, float)' has some invalid arguments`
Assets/Scripts/MovementController.cs(23,84): error CS1503: Argument#2' cannot convert object' expression to typefloat'`
Assets/Scripts/MovementController.cs(23,21): error CS0120: An object reference is required to access non-static memberUnityEngine.Rigidbody2D.velocity'`

I was hoping that someone here might have a clue as to how I can properly revise the code.

I have the code I'm using below:

using UnityEngine;
using System.Collections;

public class MovementController : MonoBehaviour
{
    public float maxSpeed = 10.0f;
    bool facingRight = true;

    Animator anim;

    // Use this for initialization
    void Start ()
    {
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void FixedUpdate ()
    {
        float move = Input.GetAxis("Horizontal");
        anim.SetFloat ("Speed", Mathf.Abs(move));
        Rigidbody2D.velocity = new Vector2(move * maxSpeed, Rigidbody2D.velocity.y);

        if (move > 0 && !facingRight)
        {
            FlipFacing();
        }
        else if(move < 0 && facingRight)
        {
            FlipFacing();
        }
    }

    void FlipFacing()
    {
        facingRight = !facingRight;
        Vector3 charScale = transform.localScale;
        charScale.x *= -1;
        transform.localScale = charScale;
    }
}

I'd prefer not to send the Unity Project, but if it's needed I can send it in a .zip over Mediafire or something similar.


texts: Deploying GWT application / LibGDX and TextureAtlas problem

texts:
I encountered with a little problem. After GWT (and LibGDX) deployment I got an error:

  GwtApplication: exception: Couldn't load image '/images/objects.png',
  file does not exist Couldn't load image '/images/objects.png', file
  does not exist

This error throws when TextureAtlas tries to load the image from settings.text file:

  images/objects.png
  format: RGBA8888
  filter: Nearest,Nearest
  repeat: none
  hills
  rotate: false
  xy: 0, 0
  size: 1024, 146
  orig: 1024, 146
  offset: 0, 0
  index: -1

I tried to use any type of path

"/assets/images/object.png"
"/clutchkick/assets/images/object.png"
"/public_html/clutchkick/assets/images/object.png"
and so on..

Any suggestions?

By the way there are no any problems on android or desktop deployment.

EDIT:
The same problem occurs when trying to load a Tmx map.


texts: Why i can not load a simple pixel shader effect (. fx) file in xna?

texts:
I just want to load a simple *.fx file into my project to make a (pixel shader) effect.

But whenever I try to compile my project, I get the following error in visual studio Error List:

Errors compiling ..
ID3DXEffectCompiler: There were no techniques
ID3DXEffectCompiler: Compilation failed

I already searched on google and found many people with the same problem. And I realized that it was a problem of encoding. With the return lines unrecognized '\ n' .

I tried to copy and paste to notepad and save as with ASCII or UTF8 encoding. But the result is always the same.

Do you have an idea please ? Thanks a looot :-)

Here is my [.fx] file :

sampler BaseTexture : register(s0);
sampler MaskTexture : register(s1)
{
    addressU = Clamp;
    addressV = Clamp;
};

//All of these variables are pixel values
//Feel free to replace with float2 variables
float MaskLocationX;
float MaskLocationY;
float MaskWidth;
float MaskHeight;
float BaseTextureLocationX;  //This is where your texture is to be drawn
float BaseTextureLocationY;  //texCoord is different, it is the current pixel
float BaseTextureWidth;
float BaseTextureHeight;

float4 main(float2 texCoord : TEXCOORD0) : COLOR0
{
    //We need to calculate where in terms of percentage to sample from the MaskTexture
    float maskPixelX = texCoord.x * BaseTextureWidth + BaseTextureLocationX;
    float maskPixelY = texCoord.y * BaseTextureHeight + BaseTextureLocationY;
    float2 maskCoord = float2((maskPixelX - MaskLocationX) / MaskWidth, (maskPixelY - MaskLocationY) / MaskHeight);
    float4 bitMask = tex2D(MaskTexture, maskCoord);

    float4 tex = tex2D(BaseTexture, texCoord);

    //It is a good idea to avoid conditional statements in a pixel shader if you can use math instead.
    return tex * (bitMask.a);
    //Alternate calculation to invert the mask, you could make this a parameter too if you wanted
    //return tex * (1.0 - bitMask.a);
}


texts: LibGDX: Scene2D Stage wont react on multiplexer input

texts:
I've got an inputMultiplexer. I want to register about two or three "systems" as processors. The classes which implementing InputProcessor get registerd by me like inputMultiplexer.addProcessor(this);. This works fine.

Unfortunately the stage which got registered very similarly

stage = new Stage();
inputMultiplexer.addProcessor(stage);

won't work. This means it won't act on any kind of user input. The strange thing is that if I don't add the other systems as processors - so the stage is the only one - it works very fine. Right now the stage gets registered as the second processor. I don't know if this could be the problem.

Do you have any idea what the problem here is?


texts: What exactly causes a surface to overlap another?

texts:
I cannot really figure out what causes one surface to overlap another. In a 3D engine I'm creating, my technique is failing in edge cases.

My method is sorting the surfaces to be painted from the furthest to the closest. To determine the closeness, I'm comparing the average z values. Sometimes, however, an overlapping surface has a higher average z value than the one it is overlapping. Thus, the surface further away is painted over the closer one - resulting in bizarre rendering like this:

What one is meant to see is the purple front surface of the cube only, whilst the red side surface is painted over the purple one. The average z value of the purple surface is higher, and therefore 'further away'. So I'm having some doubt as to whether this technique is correct.

What I also tried is getting the distance from the camera (i.e. origin) to the surface, but then I needed a point. I chose the middle of each surface but also this doesn't always seem to work because not all surfaces are as large as each other.

Therefore, what is a reliable way to determine the order of closeness of surfaces towards the origin?


texts: Adding some recoil to the Camera so that the crosshair is pushing to the sky (FPS game)

texts:
I just want to add some recoil to the camera, but I can't find a working script. It's an fps, so I take my mouse axis to rotate the camera. And now I want a pushback to the top, so that the camera looks into the sky after shooting a whole clip. It should be pretty easy, just add some amount to the axis, but it isn't working for me.

I've got something like this from another post, but it just does nothing for me... I got a feeling that my axis is locked in some way, I'm using the "MouseLook" from the standart assets.

transform.Rotate( recoil * Time.deltaTime, 0, 0 ) ;

Update:

This Script is working partially, but I think I reactivate the MouseLook too fast after the Rotate, so that the Mouse just jumps back to the starting position.

 mouseLook.enabled = false;
 transform.Rotate (-5, 0, 0);
 mouseLook.enabled = true;


texts: Why are my screenshots created through a RenderTexture too small?

texts:
Current render result:

When I am rendering image in Unity and saving as file(.png), quality of those files are reduced. They become tiny and very poor.

How can I enhance that?

Dimension of the image file is 269*168.

Code to save image :

using UnityEngine;
using System.IO;
using System;

//getty code
public class Capture : MonoBehaviour
{
    private static int resWidth = 3840;
    private static int resHeight = 2160;
    private static GameObject camObj = null;

    public static string ScreenShotName()
    {
        return string.Format("{0}/screenshots/{1}.png",
                             Application.dataPath,
                             Util.name_);
    }

    void Start()
    {
        camObj = gameObject;
        Directory.CreateDirectory(Application.dataPath + "/screenshots");
        resHeight=GetComponent<Camera>().pixelHeight;
        resWidth=GetComponent<Camera>().pixelWidth;
        //Util.everyThingHot = true;
    }

    public static void TakeHiResShot()
    {
        try
        {
            RenderTexture rt = new RenderTexture(resWidth, resHeight, 24);
            camObj.GetComponent<Camera>().targetTexture = rt;

            Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
            camObj.GetComponent<Camera>().Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
            camObj.GetComponent<Camera>().targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);
            byte[] bytes = screenShot.EncodeToPNG();
            string filename = ScreenShotName();
            File.WriteAllBytes(filename, bytes);
            Debug.Log(string.Format("Took screenshot to: {0}", filename));
            bytes = null;
        }
        catch(Exception e)
        {
            Debug.Log("Error");
        }

    }

}

Sample:

What I see during saving shot:

It's taking a lot CPU,GPU resources, renders correctly but doesn't give me what I want as a file


texts: How do I call out an IEnumerator from another script to a script which also contains IEnumerator?

texts:
It is a Game Manager:
public class gm : MonoBehaviour
public IEnumerator spawnTile() .....

I want this IEnumerator spawnTile to be called on this script:
public class gmSidePlatform : MonoBehaviour
 void Start()
{
    NextSpawnSidePlatform.x = 30.5f;
    StartCoroutine(SpawnSidePlatform());
}

IEnumerator SpawnSidePlatform()....

I did follow the instructions of calling other scripts by using Public gm gameManager1;
But the variables from the gm script didn't appear on this (gmSidePlatform) script. I don't know what to do...


texts: Issues with background coordinate configuration in objective c with runAction?

texts:
In my game I want to have two backgrounds going one after the other creating a continuous loop moving to the left. However, right now one goes, and the other does not follow it.

Here's what I currently have, which isn't working.

if((self = [super init]))
{

    self.isTouchEnabled = YES;

    background=[CCSprite spriteWithFile:@"testbackground88.png"];
    [self addChild:background z:1];
    background.position=ccp(500,240);
    id repeat1 =[CCRepeatForever actionWithAction:[CCSequence actions:
                                                         [CCMoveTo actionWithDuration:7 position:ccp(-300,240)],
                                                         [CCPlace actionWithPosition:ccp(800,240)],nil]];
   [background runAction:repeat1];

    background2=[CCSprite spriteWithFile:@"testbackground92.png"];
    [self addChild:background2 z:1];
    background2.position=ccp(500,240);
    id repeat2 =[CCRepeatForever actionWithAction:[CCSequence actions:
                                                         [CCMoveTo actionWithDuration:7 position:ccp(-300,240)],
                                                         [CCPlace actionWithPosition:ccp(800,240)],nil]];
   [background2 runAction:repeat2];
}


texts:
My question is about scalable vector graphics focused on Android.

I know that the advantage of using vector images instead of png is that you can draw it in almost every device without modifying it. The drawback is that they're very slow.

But if you convert them into png images during the runtime and then you serialize them? You obtained all the advantages without drawbacks? Or there are other reasons to avoid svg?


texts: How can I prevent a latitude/longitude based chunk system from Mercator projection stretching?

texts:
I'm working on an little mapbox based game and I'm currently working on an latitude/longitude-based chunk system. The distance between each of them should be the same. As you can see in the example the width and height of each chunk are equal. The little grey square is just the chunk middle. Those chunks were created near latitude/longitude zero, where they aren't effected by the Mercator projection.

But due to the Mercator projection the distances between the chunks are increasing as more as they move away from the middle (they look kinda stretched).

As you can see the distances between each one aren't equal anymore. The height of each of those chunks did increase. Here's another picture of the Mercator projection to visualize what I mean:

The chunks of the first picture were created near the middle of the word map (where the big black upper arrow points towards). The chunks from the second pictures were created near the bottom of the world map, where the other arrow points towards.

The type of game I'm developing requires equal chunk sizes and also it doesn't look that good when at some point the chunks look different due to the stretching.

I want to achieve a chunk system like this on the mercator projection :

I calculate the chunks as follows:

First we need the player latitude/longitude coordinates : 3.0146683, 5.3046076

One latitude is about: 110.57 km -> 110570 meters.
One longitude is about: 111.32 km -> 111320 meters.

One chunk should be about 750 meters on the map.

Because latitude and longitude got different ranges we need to adjust the chunk size.

One latitude factor = 110570 / 750 = 147,43.
One longitude factor = 111320 / 750 = 148,42.

One latitude chunk size = 110570 / 147 = 750 meters.
One longitude chunk size = 111320 / 148,42 = 750 meters.

(Maybe this step is unnecessary)

Now we convert the Lat/Lng to meters.

Latitude in Meter = 3.0146683 * 110570 meters = 333 331.873931 Meters.
Longitude in Meter = 5.3046076* 111320 meters = 590 508.918032 Meters.

Now we need to calculate the meters till the last chunk by using modulo.

Latitude Modulo => 333 331.873931 modulo 750 = 331 meter.
Longitude Modulo => 590 508.918032 modulo 750 = 258 meter.

After that we are able to calculate the Latitude and Longitude chunks.

Latitude chunk position = 333 331.873931 - 331 = 333 000.873931.
Longitude chunk position = 590 508.918032 -258 = 590 250.918032.

When we didive that now through the chunk size we get the actual chunk position.

Chunk X = 333 000.873931 / 750 = 444,0011.
Chunk Y = 590 250.918032 / 750 = 787,001.

Rounded: Chunk X = 444; Chunk Y = 787.

Now we know that the player stands right in this chunk [444;787].

In the next step I just calculate the Chunk X and Y back to latitude and
longitude and convert them via transform.AsUnityPosition to 3D coordinates,
where I place those grey objects then.

So basically I need a way to have the same visual distance between each of those chunks. Or either a way to change the projection from Mercator to a square projection, where nothing is stretched. I never worked with mapbox/Google Maps before... so I'm a newbie. Or is there maybe a formula I can use to prevent my chunks from being stretched by the projection?

Thanks for your time and attention! :)


texts:
I imported a .3ds file from skethup and in the preview it shows it with the texture, but when I put it in the scene it shows it without the texture.

http://puu.sh/gyYSU/a09541420c.png


texts: How can I loop over waypoints to move all the objects between them?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waypoints : MonoBehaviour
{
    public enum RotationMode
    {
        Normal, Curved
    }

    public GameObject objectToDuplicate;
    public Transform[] waypoints;
    public float movingSpeed;
    public bool randomSpeed = false;

    private GameObject[] prefabsToMove;

    private void Start()
    {
        prefabsToMove = GameObject.FindGameObjectsWithTag("FrameLine");
        DuplicatePrefabEffects(prefabsToMove.Length);
    }

    private void DuplicatePrefabEffects(int duplicationNumber)
    {
        for (int i = 0; i < duplicationNumber; i++)
        {
            var go = Instantiate(objectToDuplicate);
            go.tag = "Duplicated Prefab";
            go.name = "Duplicated Prefab";
        }
    }

    private void WaypointsAI()
    {
        for (int i = 0; i < waypoints.Length; i++)
        {
            if (randomSpeed)
            {
                movingSpeed = Random.Range(1, 20);
            }
            prefabsToMove[i].transform.position = Vector3.MoveTowards(
                         prefabsToMove[i].transform.position,
                         waypoints[i].position,
                         movingSpeed * Time.deltaTime
                     );
        }
    }

    void Update()
    {
        WaypointsAI();
    }
}

The problem is inside the loop there might be less or more prefabsToMove then waypoints so it will throw exception.

Then doing prefabsToMove[i] is wrong.


texts: UE4 tips how to handle Minigolf Multiplayer

texts:
Heyo!

I'm doing a Minigolf multi-player game right now. What I couldn't figure out by now is how to set up the game logic of the actual game. So where to keep track of all players being in bounds, the scores or when everyone is in the hole to load the next hole. And how do that anyway? Do I keep different versions of the same map with different spawns and travel there after that  or can I move somehow spawns and everything else staying in the same level?

I'm sorry if this is confusing or there is not enough information to follow me there. Please aks when something is unclear!


texts: PyGame custom isometric engine : caching or not?

texts:
In the game I'm making, I need an isometric view with some altitude, which means players can go behind a hill, and be partly or totally hidden. To avoid re-drawing the whole view tile after tile every time a player moves, I decided to put each horizontal line of tiles in cache and draw each line, one after another from top to bottom. This works pretty well, I think FPS are correct and everything, but memory usage could soon be a problem: a 50*50 map means 99 lines resulting in 98Mo, a 100*100 map means 199 lines and 388 Mo.

Here is a line:

The memory consumption will grow even bigger if I allow higher altitude (each line will be stored in a higher Surface object).

I'm wondering if this cache system was really a good idea... I could code a bit better so that lines are stored in the smallest possible Surface, but there will still be a big memory consumption.

Do you have any advice, any feedback on my system? Is it worth optimizing, or should I forget this cache-idea ?


texts: OpenGL interleaved position and normal data

texts:
I have an OpenGL question!

Say I have data, interleaved in the format

[vec3 normal, vec3 vert1, vec3 vert2, vec3 vert3]

all stored in one VBO (one set per triangle).
My vertex shader would have the following attributes:

in vec3 normal;
in vec3 position;

Is it possible to extract the data this way? Or would I need to duplicate the normal for each vertex (eg. [vec3 normal, vec3 vert1, vec3 normal, vec3 vert2, vec3 normal, vec3 vert3])?


texts: How do history generation algorithms work?

texts:
I heard of the game Dwarf Fortress, but only now one of the people I follow on Youtube made a commentary on it... I was more than surprised when I noticed how Dwarf Fortress actually generates a history for the world!

Now, how do these algorithms work? What do they usually take as input, except the length of the simulation? How specific can they be?

And more importantly; can they be made in Javascript, or is Javascript too slow? (I guess this depends on the depth of the simulation, but take Dwarf Fortress as an example.)


texts: Unity Prevent reloading of edited files packages

texts:
I had to make a change in the existing Universal Rendering Pipeline's ShadowCaster2D.cs to suit my needs. But every time I reload the project, the file gets reset. How do I prevent this?
The file that I need to keep is found in the following path:
(Unity Project path)\Library\PackageCache\com.unity.render-pipelines.universal@7.1.7\Runtime\2D\ShadowCaster2D.cs


texts: What should I use instead of randomized start positions for good-looking 2D rain?

texts:
Right now I'm randomizing the position of my 2D rain's spawn positions on both the X and, slightly, on the Y axis. It looks pretty weird right now, it has a bunch of huge clumps and unfilled areas:

I want a more uniform, but not a completely boring and uniform distribution of my rain. I want something that doesn't look like a perfectly tiled texture, but doesn't look as crazy random as the picture above. What can I do?


texts: per-pixel collisions using Libgdx Java (is there existing class for this??)?

texts:
I am making a simple side scrolling space shooter game using Libgdx and everything is going nicely. However until now I haven't been testing collisions for my players ship with other ships. I have lasers colliding with baddie ships using simple rectangle overlap method that exists already in libgdx.

But the "white/transparent" space around the edge of many of my sprites is quite a lot and when i am now applying the code to check collision with my player it is happening from a long way off from actual collision.
In the past I used XNA Framework C# and there was quite a simple way to do a box collision and then within that test if both pixels in question where transparent and ONLY WHEN both pixels were NOT transparent would it return true as a collision.

I'm really struggling to find this method or how to implement this using LibGDX , can anyone help me out here??

Here is the code snippet in question, if you need the full games code please let me know:

        if (ship.getBoundingRectangle().overlaps(baddiePurple.getBoundingRectangle())){
        purpleDyingSound.play();
        KillPurpleSoloEnemy();
        game.setScreen(new MenuScreen(game));
    }

Of course I'm aware that I could just trim down all the images to have almost zero transparent edges but the problem with doing that is they are animated sprites in sprite-sheets and i can't get them into the right position if I try that. (Also, I plan on having LOTS of different enemies etc and trimming would be a major ballache)

THANKS IN ADVANCE FOR ANY HELP! peace out!


texts: Raycast will not hit generated box colliders at initialization

texts:
In my map class I have an algorithm that is generating and merging box colliders together. These belong to the layer "Ground".

After that, in some places on my map I'm generating some new cubes on-the-fly, and some of these cubes I don't want to generate at all. So, I'm doing a raycast to determine if they should be added or not.

I'm doing these raycasts to check if the position they should be generated at have free space to the left and right. For both rays I'm checking if they hit a collider beloning to the layer "Ground".

But I don't get a hit at all!

I've tried to create two cubes in the editor and assign them to the layer "Ground". If I run the game then I get a hit between these two cubes. But I will never get a hit checking against my generated colliders.

I do this logic in the Start-method, is there any certain method in the life cycle when I can start to use my generated box colliders?


texts: (XNA) Possible to hide, compress, or rename .XNB files?

texts:
I'm fairly new to XNA (only a week into C# and XNA at this point) but I have been developing games for a while now, and the program I used did not require any/many external files in creating an executable. I am perfectly fine with external files (for the most part) but reading around, it seems as if .XNB files are easily accessed for others to pull your resources out of.

After some thinking, I was wondering if it was possible to do any of these 3 things:
1. Hide the .XNB files within the .exe in which case it would likely create them in an external location only during run-time (wouldn't really solve the main issue, but still)?
2. Compress many of the .XNB binaries into a single binary (such as 1 for sounds, 1 for sprites, etc.)
3. (This one is one simply for my own OCD) Change the extension name from .XNB to something of my choosing? For example, to .DAT instead to make it less of a direct indicator I used XNA and/or these files can be accessed with an .XNB ripper?

None of these would particularly solve my initial problem, but I still wonder if they are possible. Anyhow, thanks in advance guys!


texts:
I'm making a simple space game in JavaScript, but now I've hit a wall regarding vectors.

The game view is top-down on a 2d grid.  When the user clicks on the grid, the space ship will fly to that spot.

So, if I have two sets of points:

{ x : 100.2, y : 100.6 }; // the ship
{ x : 20.5,  y : 55.95 }; // the clicked coordinates

If the game loop ticks at 60 iterations per second, and the desired ship velocity is 0.05 points per tick (3 points per second), how do I calculate the new set of coordinates for the ship for each tick of the game loop?

p.s. I do not want to account for inertia, or multiple vectors affecting the ship, I just want the ship to stop whatever it is doing (i.e. flying one way) and move to the clicked coordinates at a static speed.


texts: How can I duplicate this color/hue shifting effect in C#?

texts:
I am looking for a way to duplicate this color shifting effect:

I don't think it matters but the starting frame would be this:

My instinct was that some type of hue shift is occurring in a way that causes it to loop back over. The problem arose when I saw that the source of this effect was taking any image of any color palette and reducing it to this effect, always taking 14 frames to finish the loop.

Input frame:

Result of effect:

I'm not sure how this effect is being performed, I'm hoping someone will be able to help me duplicate it. This is for a game where I'm using C#. If I can get something working in C# I'll probably move it over to a shader. I'm using the MonoGame platform.


texts: I've been googling this for a while and haven't been able to find anything (blenders importer does not work). How can I import a .x file to 3D Studio Max? There are heaps of resources in converting formats readable by Max to .x but not the other way around.


texts: Register Game Object Components in Game Subsystems? (Component-based Game Object design)

texts:
I'm creating a component-based game object system. Some tips:

GameObject is simply a list of Components.
There are GameSubsystems. For example, rendering, physics etc. Each GameSubsystem contains pointers to some of Components. GameSubsystem is a very powerful and flexible abstraction: it represents any slice (or aspect) of the game world.

There is a need in a mechanism of registering Components in GameSubsystems (when GameObject is created and composed). There are 4 approaches:

1: Chain of responsibility pattern. Every Component is offered to every GameSubsystem. GameSubsystem makes a decision which Components to register (and how to organize them). For example, GameSubsystemRender can register Renderable Components.

pro. Components know nothing about how they are used. Low coupling. A. We can add new GameSubsystem. For example, let's add GameSubsystemTitles that registers all ComponentTitle and guarantees that every title is unique and provides interface to quering objects by title. Of course, ComponentTitle should not be rewrited or inherited in this case. B. We can reorganize existing GameSubsystems. For example, GameSubsystemAudio, GameSubsystemRender, GameSubsystemParticleEmmiter can be merged into GameSubsystemSpatial (to place all audio, emmiter, render Components in the same hierarchy and use parent-relative transforms).

con. Every-to-every check. Very innefficient.

con. Subsystems know about Components.

2: Each Subsystem searches for Components of specific types.

pro. Better performance than in Approach 1.

con. Subsystems still know about Components.

3: Component registers itself in GameSubsystem(s). We know at compile-time that there is a GameSubsystemRenderer, so let's ComponentImageRender will call something like GameSubsystemRenderer::register(ComponentRenderBase*).

pro. Performance. No unnecessary checks as in Approach 1.

con. Components are badly coupled with GameSubsystems.

4: Mediator pattern. GameState (that contains GameSubsystems) can implement registerComponent(Component*).

pro. Components and GameSubystems know nothing about each other.

con. In C++ it would look like ugly and slow typeid-switch.

Questions:
Which approach is better and mostly used in component-based design? What Practice says? Any suggestions about implementation of Approach 4?

Thank you.


texts: Unity gravity not effecting everyone like it should

texts:
so My problem is a bit weird. I have a model that will not fall at the correct speed. She falls incredibly slowly. This is the only script attached to her, and I did the "Scale to large" test by placing a box next to her and letting them drop at the same time. The box fell instantly to the ground and she just kind floats taking her time.

Gravity is on kinematic is off, I'm out of ideas and could use some help. :D!

Thank you.

This is unity in c#.

using UnityEngine;

using System.Collections;

public class PlayerController : MonoBehaviour {

// public variables
public float speed = 1.5f;
public float JumpH = 1.5f;
public float RotateSpeed = 30f;

//pivate component checks
private Animator animr;
private Rigidbody LillyRB;

//private generic bits.
private bool checker;
private float movever;
private float movehor;
private float turn;

void Start (){
    LillyRB = GetComponent<Rigidbody> ();
    animr = GetComponent<Animator> ();

}

void FixedUpdate () {

    // movevertical and move horizontal check for player input wasd
    // jump checks for jump/spacebar.

    movever = Input.GetAxisRaw ("Vertical");
    movehor = Input.GetAxisRaw ("Horizontal");
    turn = Input.GetAxisRaw ("mouse x");
    Quaternion rot = LillyRB.rotation;

    Quaternion Exturn = Quaternion.Euler (0.0f, RotateSpeed * Time.deltaTime *  turn + rot.eulerAngles.y, 0.0f);

    if (movehor != 0 || movever != 0) {
        checker = true;
    }
    else {
        checker = false;
    }

    animr.SetBool ("IsMoving", checker);
    LillyRB.MoveRotation (Exturn);
    LillyRB.MovePosition (LillyRB.position + (transform.forward * movever));
    LillyRB.MovePosition (LillyRB.position + (transform.right * movehor));

}

}


texts: Fuzzy State Logic or Finite State Machine for AI

texts:
My question is regarding the use of fuzzy state logic and finite state machine with AI. What I would like to know is what the key benefits are for both and also some examples of situations where you might want to use a particular state machine. My main areas of interest are the questions the follow.

Which is better for group AI?
Which is better for individual AI?
Which is more efficient?

Also some links to any demos of each that exist would be really cool!

Thank you all who answer/comment!


texts:
When we sample a texture resource through an SSO in HLSL, how is the mip level selected for sampling; assuming the texture resource contains mips?

The SSO has parameters that seem to be concerned with the sampling method, but I can't find any documentation anywhere that states how to actually select a mip level.

Or is it done automatically as a function of the NDC depth value?

Thanks.