texts: What is the right way to use a QStateMachine for a text adventure game?

texts:
I have seen a couple topics about this already but they were a bit vague for me so I decided to make this. I'm working on a little adventure game just for fun in Qt, its basically just text on the screen and the player inputs commands into a line edit widget which I then process and do the related action/event. Thing is, I am a little confused on how to approach this. I don't want to dig myself a hole by manually coding in lots of commands and events per room because it seems to just be a pain later on. So then I thought about using some sort of database to store the information but which one should I use? I would love some advice from people who have tried something similar.

And here, these pictures are a rough outline of what I am trying to do.

Edit: I should add, the tiles for the level basically work like this. The light gray is a direction the player can move in, the dark gray parts are walls and the colors are various different actions you can do.

I don't particularly care for code, but I would like suggestions on what tools to use for this and maybe how to set them up right.


texts: Is native performance of C++/C etc. relevant for game servers?

texts:
I am wondering if the performance of unmanaged languages like C++, Rust etc. is relevant when developing a game server or is it more about the network. For game clients, it makes sense and is probably preferred.

Do you think using C# or some language like even Python would be comparable to writing game server in C++ or some other natively-compiled language?


texts: How to split a group of tiles in a grid into separate groups if a break occurs between tiles?

texts:
I have a grid where objects can be placed down by the player.  Each object that gets placed down is added to a dictionary where the key is the grid position.

Each object that gets placed down either gets added to a new zone, or added to an existing zone if any of the neighbors are in an existing zone.  If there are multiple zones, then it just picks the first one it finds and adds it.

The issue I am struggling with is how to handle splitting up zones if an object is removed from the grid.

In the first image I have 2 zones.

In the second image, I add a new object to the grid, because that tile contains 2 neighbor tiles that are in a zone, it merges the 2 zones into one.

In the third image, I remove an object from the grid, which removes it from the zone, and in this case it creates 2 new zones (but could be more depending on neighbors).  This is where I am struggling to work out the best way to efficiently do this.

I have a grid array that holds all objects placed on the grid.
A zone contains a list of tiles that are in that zone.
Each tile in a zone also gets a zone id.

What would be a fast efficient way of splitting up a zone into multiple zones?

I thought about checking all the tiles in the zone by checking its neighbors, but thought that it could be quite slow, as a zone can grow to be very big over time (zones can auto merge as well).  Also wouldn't there be a chance of an endless loop?


texts:
I am building my own 2D engine and I try to handle the progression of my character.

For example, when the player has a special item an door opens or when he talks with someone and has an item, the person reacts in a different way.

I don't want to hardcode that. Is there an common way to handle such things?
I thought about a FSM to handle that but it seemed too complex for it. (I want an easier way.)

At the moment I handle it with several if statements that check if the characters items array has item X then say this and if he has item Y then say that.

PS: I am writing my engine in JavaScript so if you post code, I can live with Java and AS 3, but not with C/C++.


texts: Draw a sphere with a custom material from script

texts:
How can I spawn or draw a sphere with a custom material with a script?

So far I've tried using Gizmos.DrawSphere, but I can't find a way to control the material used to draw it.

I would like to draw it with a material with some specularity, around 0.5.


texts: Can I my iOS-based editor save .plist files that my Mac game can read?

texts:
I want to make an editor on iOS which will record touch positions into a file. That file (in the .plist format) will eventually be used for positions in my Mac connect-the-dots game.

Can I save one .plist file to my Mac from an iOS app?


texts: How to generate a multiplier map for radiosity

texts:
I am following this tutorial: here
I am at the part where you are creating a hemicube.
I have got the code to render the scene into a texture and therfore an array.

Now how can I generate a so-called "multiplier map" for use given these
parameters: width, height, camera location, camera direction/normal.

I want the multiplier map to be stored in an array like this:

unsigned char* mult0 = new unsigned char[width*height];

I will have 5 of these maps for each side of the hemicube.


texts: Do I really need to "learn" C# for XNA if I know Java?

texts: I want to start developing in XNA. As of now, I do not know C#, but I would consider myself "good" at Java. I have looked at some C# code and it looks almost identical to Java. After looking at Java and C# Comparison, it looks like they are basically the same. Obviously some function names are going to be different, but I think I can handle it. Now if I want to learn game development in XNA, do I really need to "learn" and master C#, or can I just jump right in and learn along the way? I should also mention, I also know  PHP which looks very similar.


texts:
Let's imagine I have a breakout game. I make a level like this:

For columns < max columns
    For rows < max rows
        Create sprite from file, put it on some position based on
        current column and row, put it into array of objects.

Now, imagine I have 100 levels and I want them to be different. What tools should I use to ease my life? How do I load a level from file? Maybe a plist?


texts: Find transformation to align two polygons at fixed points?

texts:
Problem

I have a source image (arbitrary width and height c) shown here as a rectangle [X1,X2,X3,X4]. It contains two points C and D (both known coordinates within the image - X4 / top left).

Then I have a target image (might have different height a and width b than source image) that contains two points A and B (|AB| doesn't necessarily equal |CD|). There's also a source of projection S.

I need to somehow calculate coordinates of a transformed rectangle (polygon) such that:

Point C will always be mapped to A (therefore A will be equal to C) and D will be mapped to B (B = D)
Point X3 of this newly calculated polygon will lie on a line between S and A/C (now identical)
Point X4 will lie on a line from S to B/D.
Distance from parallel lines [X1,X2] and [X3,X4] will be still c. (If it turns out that it's not always possible to construct such a polygon the condition 4. can be dropped, and [X1,X2] don't need to be parallel to [X3,X4] as well)

(see below)

What I've tried

I thought I will solve it by:

shrinking width of source image by ratio of |AB| and |CD|
aligning C with A (move source image)
finding angle difference  between AB and CD
rotating source image by angle  (with center in C/A)
calculating X3 and X4

But it doesn't work universally. Steps 1-4 work well, but then changing X3 and X4 moves C (resp. D) away from A (resp. B).


texts:
Im working with my deferred engine in XNA 4.0 and Im combining it with a forwardpipeline to support semi-transparency and other "forward only" effects.

Let me describe what I do:

Render GBuffer and all deferred geometry based on materials
A final composit where I combine the lightbuffer and the diffusebuffer
from the GBuffer. I output color and depth to a rendertarget so I
can use forward rendering to draw directly onto that RT.
Render forward geometry
I then take the RT from the forward pipeline and do postprocessing
stuff.
Finally I write the RT to the backbuffer

Question:

As you can see in the image below there's a problem with the
boundingboxes. The are drawn using forward rendering and is drawn
using the depthbuffer I descibed in step 2. I have tried to offset
the depthbuffer in different directions with a texel or two. But
nothing seems to solve the problem. Has anyone experienced this
problem before?

EDIT:
   This post has been cleaned from some statements to avoid confusion.


texts:
I am going to use a specific example in my question, but overall it is pretty general. I use java and libgdx.

I have a ship that moves through space. In space there is debris that the ship can tractor beam in and and harvest. Debris is stored in a list, and the object contains it own x and y values. So currently there is no way to to find the debris's location without first looking at the debris object. Now at any given time there can be a huge (1000+) amount of debris in space, and I figure that calculating the distance between the ship and every single piece of debris and comparing it to maximum tractor beam length is rather inefficient.

I have thought of dividing space into sectors, and have each sector contain a list of every object in it. This way I could only check nearby sectors. However this essentially doubles memory for the list. (I would reference the same object so it wouldn't double overall. I am not CS major, but I doubt this would be hugely significant.) This also means anytime an object moves it has to calculate which sector it is in, again not a huge problem.

I also don't know if I can use some sort of 2D MAP that uses x and y values as keys. But since I am using float locations this sounds more trouble than its worth.

I am kind of new to programming games, and I imagined there would be some eloquent solution to this issue.


texts: Does compressing data before transfer make a game run faster?

texts: I want to make my game as fast as possible as it is real time and fast paced. I have already decided to encrypt my data here and I was wondering whether compressing it would be faster for the client and the server? Also I was wondering if it is better to encrypt data before or after compression.


texts: How do I calculate UV space from world space in the fragment shader?

texts:
In my vertex shader I have calculated the world space

o.worldSpacePosition = mul(unity_ObjectToWorld, vertIn.vertex);

How do I convert that world space into uv space coordinates in my fragment shader?

        float4 frag(VertexShaderOutput i) : COLOR //SV_Target0
        {
            // float2 uv = i.worldSpacePosition ???

        }

I have tried

float4 mvp = UNITY_MATRIX_MVP[3];
float2 uv = mvp.xy /= p.w;

but that does not appear to work as the uv is always (0, 0)

EDIT:

I am drawing a mesh on the screen in world space coordinates which needs to lookup into a screen space texture:

The way I am currently solving this is by calculating the uvs for each vertex of the mesh using the following calculation:

camera.WorldToViewportPoint(vertices[i]);

Unity uses normalised coordinates for the viewport [0,1] rather than [-1,1].

This works fine but I wasn't sure of the behaviour if part of the polygon is off the screen.  I presume I should clamp the uv?

Screen space might not be the correct term for the uv coordinates.  Perhaps texture space is a more appropriate term?


texts: I am trying to make something with java libgdx (2D). One thing that I can't figure it out is how to check mouse intersection with (fore example) isometric textures that are not rectangle shaped images. I found something about pickingColorPicking algorithm in libgdx, but I can't find any docs about how to use it. Any ideas?


texts: How do I make a 2D World Political map in unreal engine 4?

texts:
Can someone explain the basics of making a 2D World map in unreal engine 4 (e.g. similar to the ones used in Plague inc., age of civilizations, etc.)

I've seen it being done in unity, but couldn't find any similar content in unreal engine 4...

Thank you.


texts: Detecting wins in peer to peer RTS games like Starcraft

texts:
A typical RTS game is implemented with the standard networking model: peer to peer lockstep.

Consider Starcraft 2, given that Battle.net presumably doesn't know anything about the state of game given that there is only communication between the two players in a peer to peer model, how does Battle.net know who was the winner in the end. Relying on the two peers to not try to cheat and report accurate results is naive.


texts: How to run code as an instance you just created in GML

texts:
Alright, I'm looking how to create an instance, and then run a chunk of code on the instance I just created, and not have that code run on any other duplicate instances.

Noob question, I know. Please help though?


texts:
My game consists largely of "sea" tiles and areas of tiles to form "islands". Each "sea" tile is exactly the same.

The map is initially large and going to get larger. I'm trying to reduce the map size since, the majority of it is the same.

My initial thought:
Store just the islands with their locations within the map. The map consists of, total map size and islands only.

Any other suggestions or perhaps how I could implement the above whilst still being able to use a* pathfinding?


texts: How to make a cylindrical collider for a cylindrical mesh in UE4

texts:
When I am importing Axis Alligend cylindrical mesh in UE4 here is what I get as an automatically generated collider:

But if I rotate the mesh in Maya and again exprot FBX to improt in UE4 here is what I get:

As you can see the object is the same but the collider is much worse. How can I make the same callider in spite of the orientation of the cylinderical mesh?

BTW if I remove collider and do auto convex collider:

I get this:

Which is very good but the problem is that I want it to be generate from the beginning and not later when I edit the mesh collider. How can I achieve that?


texts: Unity fails to effectively split spritesheet

texts:
I'm very new to game development and I find it very difficult to split the spritesheets available at opengameart.org. All of them are kind of jumbled together without any fixed grid.
The resource I learned from always used neatly assembled sprite sheets and Unity would have no trouble in automatically splitting them. But almost all are randomly placed and Unity cannot split them.
For example:

And below is the automatic splitting in unity:

How do you guys get the sprites from such spritesheets in unity? Some guidance would be appreciated.
Thank you


texts:
I have converted my C# game from OpenTK (OpenGL) to SharpDX (DirectX) and have it up and running from Visual Studio 2010. I also have it up and running from Visual Studio 11 in Metro, in the Windows 8 Developer Preview. However, the Metro build is still lacking textures, so my polygons are simply colored right now. The problem is that the methods used to load images are absent in the Metro DLLs. These methods are all missing from the Texture2D class (inherited from the Resource class) in Metro:

SharpDX.Direct3D11.Resource.FromStream
SharpDX.Direct3D11.Resource.FromFile
SharpDX.Direct3D11.Resource.FromMemory

Does anyone know if these will eventually be implemented in Metro? Or is there an alternate approach I could be using? Please keep in mind that I never knew a thing about DirectX or SharpDX before this, so I'm still very wet behind the ears with all this.

Finding any kind of help or information for SharpDX is not easy, which is a shame, because it seems to be a great solution for 3D in Metro using C#.


texts: How should I check if object is null or not?

texts:
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SavedGamesSlots : MonoBehaviour
{
    public GameObject saveSlotPrefab;
    public float gap;

    private Transform slots;
    private string[] imagesToLoad;

    // Start is called before the first frame update
    void Start()
    {
        string imagesFolder = Path.Combine(Application.dataPath + "/Saved Screenshots");
        if (!Directory.Exists(imagesFolder))
        {
            Directory.CreateDirectory(imagesFolder);
        }

        imagesToLoad = Directory.GetFiles(imagesFolder, "*.png");

        slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        if (imagesToLoad.Length > 0 && slots != null)
        {
            for (int i = 0; i < imagesToLoad.Length; i++)
            {
                var go = Instantiate(saveSlotPrefab);
                go.transform.SetParent(slots);

                Texture2D thisTexture = new Texture2D(100, 100);
                string fileName = imagesToLoad[i];
                go.GetComponent<RawImageInfo>().FolderAndFileName = fileName;
                byte[] bytes = File.ReadAllBytes(fileName);
                thisTexture.LoadImage(bytes);
                thisTexture.name = fileName;
                go.GetComponent<RawImage>().texture = thisTexture;
            }
        }
    }

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

    }
}

I'm checking in this line if slots is not null :
if (imagesToLoad.Length > 0 && slots != null)

The problem is that I'm getting exception null already on the line before :
slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

The reason is that the object with the tag "Slots Content" is disabled when the game start and I want it to be disabled when the game start but I also don't want to get this null exception. Then how should I make the null checking ?
I tried also :
if (GameObject.FindGameObjectWithTag("Slots Content").transform != null)
            slots = GameObject.FindGameObjectWithTag("Slots Content").transform;

        if (imagesToLoad.Length > 0 && slots != null)

But still getting the exception null on the check :
if (GameObject.FindGameObjectWithTag("Slots Content").transform != null)


texts: Unreal: Y-Axis boundary on a Camera Bounding Box

texts:
I was wondering if I could get some help with modifying a Blueprint I'm currently using for a project in Unreal Engine.

I am currently attempting to make a side-scrolling platformer game and I'm using a camera bounding box Blueprint to restrict where the camera can move when tracking the player's movement, based on the following series of tutorials on YouTube by JvtheWanderer: How to make a Metroidvania/ 2D Camera Blueprint System on #UE.

The camera bounding box works as intended, in that it prevents the camera from moving beyond the limitations of the camera box placed within the scene, but I want to go even further than that and establish a limitation within the camera bounding box that not only limits the camera's movement but also prevents the player from moving on the Y-axis beyond the box's boundaries.

Pretty much every platformer from Super Mario to Sonic the Hedgehog to Castlevania, have such boundary limitations, usually at the very start of the level and also frequently at the end.  The limitation on the Y-axis boundary is also frequently used to lock the player into a particular area for forced enemy encounters, mini-boss fights as well as proper boss battles, a limitation that lasts until the player has vanquished the threat.

I wish to implement similar boundaries on the camera bounding boxes within my project to restrict where the player can go without having to place walls everywhere to keep the player from wandering beyond the level's limits.  Using walls to restrict the player's movement is fine for indoor areas, but it ends up looking distractedly out of place in outdoor areas if used in excess.

I've included screenshots below of the Construction Script & Event Graph from the SideScrollerCamera Blueprint I'm using. I would also include the Viewport and the Level Blueprint as well, except that the time being, I am unable post more than two links.

Construction Script:

Event Script:

Any help with this matter would be greatly appreciated.


texts: Using several render textures at the same time during runtime

texts:
I want to achieve a system where I can use render textures as portraits/icons. So when I select something I want to show it in my UI, currently I do:

Spawn my prefab with the model (I have one of these prefabs for each model), in my case this prefab has a camera (for render texture), a model, and a spotlight.
Show this render texture in my UI

This is fairly straight forward when I only need one render texture at a time. But say I select a house and want to see all residents, now I need 6-10 render textures all showing different models.
Should I create/destroy render texture assets at runtime for this type of feature, since each camera would need its own render texture? Im worried its an expensive feature that costs more than its worth perhaps.
Or do I need to create one render texture asset for each model in my game, and simply point to it in the prefab mentioned above?
Is there a smarter way?


texts: How do I refer to a native library with Unity 5 on Android?

texts:
I have a library called mylibandroid.a. This is given to me by another developer. I also have the iOS version of this lib, and have been able to access it from Unity.

It is supposedly built for android. I have included it in my Plugins folder in my Unity 5 project, but I renamed it mylibandroid.so as droid libs use this naming convention. I can see the library included in the .apk file, so Unity seems to know it should go in there.

My code looks like this:

public class AlmoTest : MonoBehaviour
{
#if UNITY_ANDROID
    [DllImport("mylibandroid.so")]
    private static extern void FreeGlobals();

    public void TestFreeGlobalsButtonPress()
    {
        Debug.Log("Pressed");
        FreeGlobals();
    }
#endif
}

When my function is called, I get this error:

E/Unity   ( 4188): Unable to find mylibandroid.so
I/Unity   ( 4188): Pressed
I/Unity   ( 4188):
I/Unity   ( 4188): (Filename: ./artifacts/generated/common/runtime/UnityEngineDebug.gen.cpp Line: 56)
I/Unity   ( 4188):
I/Unity   ( 4188): DllNotFoundException: mylibandroid.so
I/Unity   ( 4188):   at (wrapper managed-to-native) AlmoTest:TestFreeGlobalsButtonPress ()
I/Unity   ( 4188):   at AlmoTest.TestFreeGlobalsButtonPress () [0x00000] in <filename unknown>:0


texts: How should browser based muiltiplayer game state be syncronized using WebSockets and a Node.js backend?

texts:
I'm in the process of learning how to create browser based html5 games. I'd like to eventually be able to achieve a game with mechanics very similar to that of the game agar.io. I've been observing coding streams and doing a fair amount of reading on the subject of network latency, jitter, and buffering but I'm still having difficulty ironing out an appropriate aproach to coding a node.js implementation to handle these things. I'm not so much as interested in having a solution provided to me as learning how more expierenced developers code tick counts, frames, etc...

Thank you all very much for your time and I very much look forward to any input your willing to provide regarding the subject. :)


texts: MonoGame HLSL fx using Multiple Textures

texts:
I'm converting an old XNA title to MonoGame and one of the HLSL fx files uses two textures. But no matter what I do, it only ever uses the screen texture while rendering the effect in MonoGame, or else draws nothing.

I can see in debug mode that I'm trying to pass in the correct textures in C#, plus it works correctly in the XNA version. So why is my shader only using the screen texture in Monogame?

HLSL

Texture2D ScreenTexture;
sampler2D ScreenSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

Texture2D DistortionMap;
sampler2D OffsetSampler = sampler_state
{
    Texture = <DistortionMap>;
    AddressU = Clamp;
    AddressV = Clamp;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Use the DistortionMap to alter the location of the ScreenSampler output.
    // DistortionMap's rg at a position correspond to that position's xy distortion.
    return tex2D(ScreenSampler, texCoord + (tex2D(OffsetSampler, texCoord).rg * 2 - 1));
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

C#

public static void Draw(SpriteBatch spriteBatch)
{
    // Update the Offsets map texture.
    UpdateVertices();

    // Set up the current render target to draw to the other render target
    Game1.RenderSetToA = !Game1.RenderSetToA;
    ThisGame.GraphicsDevice.SetRenderTarget(Game1.RenderSetToA ? Game1.RenderTargetA : Game1.RenderTargetB);
    RenderTarget2D renderTargetToDraw = Game1.RenderSetToA ? Game1.RenderTargetB : Game1.RenderTargetA;

    // Draw the old render target with the distortion effect to the new render target.
    DistortionEffect.Parameters["ScreenTexture"].SetValue(renderTargetToDraw);
    DistortionEffect.Parameters["DistortionMap"].SetValue(Offsets);
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, null, null, null, DistortionEffect);
    spriteBatch.Draw(renderTargetToDraw, Vector2.Zero, Color.White);
    spriteBatch.End();
}


texts: Unity, changing gravity game & stopping character when he hit a wall

texts:
I am currently working on a 2d puzzle game in the unity engine. One of the aspect of this game is the possibility to rotate the level of 90°. It also rotate the gravity.

The main character is not directly controlled by the player, but instead falls when the level is rotated.

When the main character hits a wall, he should stop to moving. If I do not stop it, it kind of blinks and shakes against the wall.

To stop it I detect collision and depending on the current rotation state, the player will stop at "vertical" or "horizontal" tags when a OnCollisonEnter occurs. I must do that because when the player falls on his relative ground, he must not stop like if he had touched a wall.

My problem is the 'side' of platform, or the 'top' of wall, they use the same tag and thus do not give the correct tag to my character. I tried to put a very small invisible box on top/side of elements but the collision occurs nevertheless. It seems when the player falls and hit something he go through a bit before being replaced at correct position by unity.

Is there a way :

1 ) to not stop my character but to make it appear immobile on screen

2 ) To detect a "I cannot move anymore" collision other than by using collision?


texts: Can I pause Unity Setup download and continue it whenever possible as per convenience(using Unity Hub)?

texts: Actually I get only 1.5GB data daily. So it's not possible for me to download the whole Unity setup in a day. So I wanted to know if I can pause and resume download process as per convenience. I am downloading using Unity Hub.


texts: How do I run a physics simulation in the background, to determine possible future outcomes?

texts:
I'm designing a physics-heavy game, in 3D. The core mechanic of this game is that the user gets to choose his actions based on probable future outcomes. For example, the player has a choice whether to try option A, B, or C. When the option comes up, I want to copy the game state and world into three separate simulations, and then run the three options in super high speed to determine probable outcome. The game will then present the probable outcome for each player choice. This needs to happen instantaneously, in terms of user experience.

It doesn't have to be an exact copy of the game state; a simplified simulation can also work, as long as the current world physics state can be duplicated and simulated. How would I go about making this? I know Unity, for example, only exposes one instance of a physics world at a time.


texts:
Hi there for some reason the maskbit of my b2FixtureDef is being maxxed out and im not sure why

Here is the declaration of the items that are used in the game

enum PhysicBits {
    PB_NONE = 0x0000,
    PB_PLAYER = 0x0001,
    PB_PLATFORM = 0x0002
};

Basically what i want is the player to run along a surface is not slow down (i set platform & player friction to 0.0f)

I then setup my Contact Listener to print out the connections (currently only have 1 platform and 1 player)

Player Fixture Def

b2FixtureDef fixtureDef;
fixtureDef.shape = &groundBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.filter.categoryBits = PB_PLAYER;
fixtureDef.filter.maskBits = PB_PLATFORM;

Platform Fixture Def

b2FixtureDef fixtureDef;
fixtureDef.shape = &groundBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.filter.categoryBits = PB_PLATFORM;
fixtureDef.filter.maskBits = PB_PLAYER;

Now correct me if im wrong but these are saying the following:

Player Collides with Platform
Platform Collides with Player

Here is the printout of the fixtures colliding with each other

********    <-- Indicates new Contact
Platform
ContactA: 2
MaskA: 1
------
Player
ContactB: 1
MaskB: 2
********    <-- Indicates new Contact
Platform
ContactA: 2
MaskA: 1
------
Player
ContactB: 1
MaskB: 65535
********    <-- Indicates new Contact
Platform
ContactA: 1
MaskA: 65535
------
Player
ContactB: 1
MaskB: 65535

Here is where i am confused. On the second & third contact the player maskBit is set to 65535 when it should be 2 and there are 3 contacts when i am sure at most there should only be 2.

I've been trying to figure this out for hours and i can't understand why it is doing this. I would be very grateful is someone could shine some light on this for me

UPDATE:
**I printed out the class of the contacting objects. For some reason it seems to do the following:

First Contact: Correct Result.

Second Contact: Player b2Fixture Obtains a new maskBit.

Third Contact: Platform b2Fixture appears to be set to the same as the Player b2Fixture.
It would seem I have a memory race condition i think**


texts: Alternatives to Camera.main.ScreenToWorldPoint in Unity

texts:
What are alternatives to Camera.main.ScreenToWorldPoint in Unity?

So, here is my code (just the piece which is relevant for the question):

void sendPointerMove(ref Vector3 mousePosition)
{
    lastMousePosition = mousePosition;

    Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    PointerData pointerData = new PointerData(
       mousePositionInWorld: mousePositionInWorld
    );
}

void FixedUpdate()
{
    Vector3 mousePosition = Input.mousePosition;

    if (needToSendPointerMove(mousePosition))
    {
       sendPointerMove(ref mousePosition);
    }
}

I am using JetBrains Rider to develop for Unity. And the ide suggests me the following about my sendPointerMove function invocation inside the FixedUpdate:

  Expensive method invocation

I am sure that the issue is due to the Camera.main.ScreenToWorldPoint because when I comment out the part the warning disappears.

Thank you.


texts:
I'm creating an RPG with a theme of a hero that must restore peace to a world fallen to evil forces. It serves as an educational tool.

I'm creating a promotional website for it and using other online social tools for marketing.

I only have one focus: to make this game as great as possible for people to learn. I've seen some companies that market themselves as their product name, like DuoLingo, and some that market as the studio, such as Strawberry Games.

I don't have a game studio and have simply been marketing (FB page, website URL, etc) as the game's name, Lexicana's Destiny.

Does it really matter which way I market it? If so, why?


texts: How do you handle entity life-time and entities without all components in an ECS?

texts:
I'm just starting to implement my own ECS and am drawing everything down on paper to make sure I understand it all before tackling the implementation in code. However I'm getting stuck on entity-lifetime and nothing I've read really answers my question.

Just to be sure I'm not missing something, my understanding so far is:

Components of the same type all sit next to each other in memory
Entities are just an ID, which Components refer to (i.e. Components have an "owner")
Components all have a unique Id

Great! So for example, say I have a PositionComponent, VelocityComponent, and VisibleComponent.

struct PositionComponent {
    vector2f position;
};

struct VelocityComponent {
    vector2f velocity;
};

struct VisibleComponent {
    Image imageToRender;
};

Great. Now let's say I have two types of Entity:

EntityA has a position, velocity, and visible components
EntityB has a position and velocity component, but is not visible

(let's hypothetically say that the Image in the visible component is the actual image data because every entity is super unique or something)

Say I have an PhysicsSystem which wants to iterate over all the Position and Velocity components and update the Position. This works, because every entity I've created has both of these components.

And so we're using EntityID as an index into the component arrays, we can easily know we're accessing the correct ones.

But then if there was a RenderSystem that wants to iterate over all the Position and Visible Components, the problem is that the EntityId can no longer be an index into the arrays, because not every Entity has every component.

So; the way I've thought to address this is by having an "Entity to Index Map" for each component. Basically, this EntityID has a PositionComponent in index 232 of the array.

But because of this, now any system that needs two or more Components to act, will lose out on all the benefits of an ECS, right?

I dismissed giving all components arrays empty space to keep them all "in sync", but that means I could have a lot of wasted data, which only gets worse the more different components I create.

There's then the problem of lifetime. If EntityID 232 is killed, I ideally would shift all the components in these arrays down to fill the gap, which again means I can't use EntityId as an index into the arrays.

A solution I thought of here was to re-use EntityIDs when they're no longer needed, maybe by using a 16bits of a 32-bit ID as the actual array index, and the other 16-bits as some sort of random guid to keep it clear that it's a new entity (and not the old one who's EntityID is being reused). This means I don't need to shift the data around, and wouldn't need to keep a map from ID to Index; but it doesn't solve the problem where not all entities have all components, so none of the arrays can ever be assumed to be "in sync".

So in summary my questions are:
1. How does a System in an ECS handle iterating over two separate components, when it's not guaranteed both component arrays will have the same entities components in the same indices?
2. Is it more beneficial to keep the data compact, or keep the arrays in sync?


texts:
I am dropping bombs from a spaceship orbiting a planet. My camera is affixed to the ship.
I fire bombs by instantiating a bomb at the position of the camera, which is at all times facing toward the planet, however, the bomb is not intended to move directly toward the planet center. Rather, there is a movable crosshair between the camera and the planet and I want the bomb to move from the camera in the direction of the crosshair. My bomb script looks like this:
public class bomb : MonoBehaviour {

    public float speed;
    GameObject crosshair;

    // Use this for initialization
    void Start () {
        crosshair = GameObject.Find ("Crosshair");
        transform.SetParent (null);
        transform.LookAt (crosshair.transform);
    }

    // Update is called once per frame
    void Update () {
        transform.Translate (transform.forward * Time.deltaTime * speed);
    }

 }

My expectation is that the bomb instantiates at the camera, disassociates from its parent (the camera), turns to face the crosshair and then moves in that direction until it hits the planet.
But that's not what happens.
For reasons unknown, the projectile travels due left of the camera. So I adjust my projectile to move transform.right instead of transform.forward. And this works - half of the time.
Here's what it looks like on the West (working):

Here's what it looks like on the East (not working):

The projectiles are kind of small, but trust me, they're there.
As mentioned, my ship is orbiting the planet. If it is orbiting on one hemisphere (0:180), it shoots toward the planet, but if it is on the other hemisphere(0:-180), it shoots directly away from the planet. I can't explain this, because the camera continuously looks toward the planet, and the crosshair is always between the two, and the bomb disassociates from them anyway.


texts:
The player go's throe walls and stops when theres no wall.
Code:

package input;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.math.GridPoint2;
import com.badlogic.gdx.math.Vector2;

import dungeon.Dungeon;
import player.PlayerCharacter;
import player.Player_state;

public class PlayerInputProcessor {
private PlayerCharacter player;
private Dungeon dungeon;

private final int NORTH = 0, SOUTH = 1, WEST = 2, EAST = 3;

public PlayerInputProcessor(PlayerCharacter player, Dungeon dungeon) {
    this.player = player;
    this.dungeon = dungeon;
}

public void HandleInput() {
    Vector2 pos = player.getVectorPos();

    if(Gdx.input.isKeyPressed(Keys.UP)) {
        if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), NORTH)) {
            player.setVectorPosY(player.getVectorPosY() + 3);
        }
    }
     if(Gdx.input.isKeyPressed(Keys.DOWN)) {
        if(canmovethere(new GridPoint2( (int) player.getVectorPosX() / player.getWidth(), (int) (player.getVectorPosY() - 3) / player.getHight()), SOUTH)) {
            player.setVectorPosY(player.getVectorPosY() - 3);
            player.setState(Player_state.WALKING_FORWORD);
        }
    }
     if(Gdx.input.isKeyPressed(Keys.RIGHT)) {
         if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() + 3) / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), EAST)) {
            player.setVectorPosX(player.getVectorPosX() + 3);
        }
    }
     if(Gdx.input.isKeyPressed(Keys.LEFT)) {
         if(canmovethere(new GridPoint2( (int) (player.getVectorPosX() - 3) / player.getWidth(), (int) player.getVectorPosY() / player.getHight()), WEST)) {
            player.setVectorPosX(player.getVectorPosX() - 3);
        }
    }

    if(Gdx.input.isKeyJustPressed(Keys.E)) {
        if(player.hasSword()) {
            player.sword = false;
        }
        else player.sword = true;
    }

     player.setGridPos(new GridPoint2((int) player.getVectorPosX() / player.getWidth(),(int) player.getVectorPosY() / player.getHight()));

}
private Boolean canmovethere(GridPoint2 newpos, int die) {
    GridPoint2 nextpos = new GridPoint2();
    GridPoint2 nextpos2 = new GridPoint2();

    if(die == NORTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y + 1;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y + 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == SOUTH) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y;
        nextpos2.x = newpos.x + 1;
        nextpos2.y = newpos.y;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    if(die == EAST) {
        nextpos.x = newpos.x + 1;
        nextpos.y = newpos.y;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y + 1;
        if(dungeon.getTile(nextpos).isPassable() && dungeon.getTile(nextpos2).isPassable()) {
            return true;
        }
    }
    if(die == WEST) {
        nextpos.x = newpos.x;
        nextpos.y = newpos.y;
        nextpos2.x = newpos.x;
        nextpos2.y = newpos.y - 1;
        if(dungeon.getTile(nextpos).isPassable()) {
            return true;
        }
    }
    player.setState(Player_state.STANDING);
    return false;
 }
}


texts: Is it ok to use polymorphism as a way of "interfacing" with objects in a scene?

texts:
I'm designing a class that holds values representing a 3D scene. This includes lights, cameras, meshes, materials, etc.

The way how I'm setting it up is that each "thing" has a name. A camera has a name, a light has a name, etc. But they also have an "interface" to access the object via pointer instead of having to name it each time something needs to be changed.

For example:

Light *light = scene.getLight("light2");
light->setBrightness(2.0f);

The problems is what Light is. Ideally, it's "proper C++" where it's a pointer directly to the internal object. However, these classes are closely tied to how the scene class works, which makes maintainability a mess. It's seems much easier to just have private implementations that do all the dirty work and only let the user receive pointers to an interface.

What I want to do is make Light an interface (struct with virtual functions, no data, no non-virtual functions except empty constructor) and implement the internal details as a private class inside the scene class. While this makes it more maintainable, it comes at the cost of using polymorphism where I'm not dealing with more than one implementation.

Any thoughts or ideas are helpful.


texts: How to continuously create objects in front of the camera when moving forward?

texts:
I have created a scene in Unity3D that's filled with spheres. I want to be able to move forward forever and still be passing through the spheres.

I was thinking I'd keep the player in one spot and move the spheres. Maybe destroy the previous bunch of spheres and create a new bunch in random coordinates? I really don't have idea how to start.


texts:
I am thinking of creating a sprite base 2d top down farm simulation game. The game uses tiles and I was wondering (conceptually) what is the best way to handle the farm tiles. Each tiles should have the following list of features.

The player should be able to add seeds to each tile
The player should be able to plant a variety of vegetables.
Plants should have different stages of growth
The player should be able to interact with each tile (dig, cover holes, water, add fertilizer, etc).
The farm layout can have a variety of shapes (i.e. Not just a square (9 x 9) or rectangle (9 x 15) a shaped farm.)

Currently I have a script that generates a square or rectangle shaped like farm, each tile is a sprite object with a 2D collider. I have come up with a solution for planting and the different stages of growth. However, it isn't the most elegant solution. My current solution is to create prefab for each plant. Then once a seed is planted onto a tile, create a plant object in the location of the tile (using it's vector position), and make the plant a child object to that tile. Each plant will have an age counter that increase when a new day is triggered. To show the growth stage swap the texture depending on the plant's age.

My biggest problem with the implementation is that if the players farm is very large the game will have to create a hundreds object, which seem very taxing. Is that a different way achieve these features without the use of so many objects? If so, how would I implement it (conceptual of course). Thanks!


texts: How do I set something when 2 or more touches are pressed?

texts:
I currently have a working controller with left and right but I want to set the velocity of the character to 0/Stop when 2 or more touches are detected. This is my current working code but I want to make the player stop when 2 touches are detected.

void TouchMove(){

    if(Input.touchCount > 0){

        Touch touch = Input.GetTouch(0);

        float middle = Screen.width / 2;

        if(touch.position.x < middle && touch.phase == TouchPhase.Began) {
            MoveLeft();
        }
        else if (touch.position.x > middle && touch.phase == TouchPhase.Began) {
            MoveRight();
        }

    }
    else {
        SetVelocityZero();
    }
}`

This is how my game looks like


texts: How to transform a shadow map to camera view?

texts:
I'm making a rendering engine as a hobby to learn more about 3D. I have a deferred renderer with the G-buffer (color, normal and depth). I also have a lighting controller that uses only spotlights at the moment. For each light, I render the depth to a texture. This works nicely, but I can't wrap my head around how to map this depth map.

Basically what I would want is a view from the camera with the light's depth map mapped in the view. I've read a ton of tutorials but cannot seem to understand this process well enough.

(BTW, I'm aiming OpenGL 3.3, so no deprecated stuff in the answers. The web is full of those already :D)


texts: Implementing navigatable achievement menu in javascript

texts:
I am in the process of learning javascript for game design, and wanted to make a separate achievement page that the user can navigate to that will allow them to check their achievements on various games. (at the moment I am not concerned with implementing localstorage/cookies etc, I just want to work on the page for now)

So the requirements of my base idea is as follows:

Able to drag around the viewport/page to view all the achievement categories as they will likely not all be in view on smaller screens
Able to click on a category to open a small box containing all achievements belonging to that game/category
Able to mouse over all achievements in the boxes to get text descriptions of what they are
OPTIONAL: have lines connecting each box on the "overworld" to show users where nearby boxes are if they are off screen

At first, I thought I would need canvas to be able to do this. I learned a bit about it and got decently far until I realized that canvas has a lot of restrictions like not being able to do mouseover events unless manually implementing each one. Here is the current progress I was at in doing a test-run of learning canvas, but it's not very far:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function resize()
    {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.translate(panning.offset.x, panning.offset.y);
        draw();
    }
    window.addEventListener("resize", resize);

var global = {
    scale   : 1,
    offset  : {
        x : 0,
        y : 0,
    },
};
var panning = {
    start : {
        x : null,
        y : null,
    },
    offset : {
        x : 0,
        y : 0,
    },
};
var canvasCenterWidth = (canvas.width / 2);
var canvasCenterHeight = (canvas.height / 2);

function draw() {
    ctx.beginPath();
    ctx.rect(canvasCenterWidth, canvasCenterHeight, 100, 100);
    ctx.fillStyle = 'blue';
    ctx.fill();

    ctx.beginPath();
    ctx.arc(350, 250, 50, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'red';
    ctx.fill();
}

draw();

canvas.addEventListener("mousedown", startPan);

function pan() {
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.translate(panning.offset.x, panning.offset.y);
    draw();
}

function startPan(e) {
    window.addEventListener("mousemove", trackMouse);
    window.addEventListener("mousemove", pan);
    window.addEventListener("mouseup", endPan);
    panning.start.x = e.clientX;
    panning.start.y = e.clientY;
}

function endPan(e) {
    window.removeEventListener("mousemove", trackMouse);
    window.removeEventListener("mousemove", pan);
    window.removeEventListener("mouseup", endPan);
    panning.start.x = null;
    panning.start.y = null;
    global.offset.x = panning.offset.x;
    global.offset.y = panning.offset.y;
}

function trackMouse(e) {
    var offsetX  = e.clientX - panning.start.x;
    var offsetY  = e.clientY - panning.start.y;
    panning.offset.x = global.offset.x + offsetX;
    panning.offset.y = global.offset.y + offsetY;
}
body{
  overflow: hidden;
}
canvas {
  top: 0;
  left: 0;
  position: absolute; }
<canvas id="canvas"></canvas>

So I guess my question is now: what is the best way to implement this? Is it feasable to do it with canvas, or should I just scrap that and try to figure out something with div movement? Should I be concerned with performance issues and should that affect how I implement it?


texts: Handling (spawning/removing) entities in SFML

texts:
I am unsure which method to use to handle my enemies in SFML.

The idea that I am trying to recreate is to spawn enemies every so many seconds. Initially I wanted to do this using a vector such as std::vector SpriteVector; The advantages of this method would be that in theory it is easy to add and remove my enemies from the vector. Using the push_back and erase method.

However the error with this at the moment is that when I am trying to check whether the sprite or the arrows are hitting an enemy within my vector it will not work.

I know that I could possibly use an array to store the enemies then set their state when hit to false however I am not sure how this will effect spawning my enemies. The functionality of being able to add to a vector is what I think I will need. Otherwise I am sure not sure how to get around the issue of having a certain number of enemies within the array then spawning more over a series of time.

Is this the best way to go about the task I am trying to achieve?


texts: Does the base game I choose for a steam mod matter?

texts: Me and a couple of my friends are planning on trying to make a source mod, but we can't figure out how to tell what game to use as a base. We hope to make a totally different game with it, and aren't sure how much of the base game will actually hang around. Like if we chose TF2 for the base would we be stuck with cartoony graphics and teams?


texts:
So I am making a death animation for a game. enemy1 is a UIImageView, and what I'm doing is when an integer is less than or equal to zero, it calls this deathAnimation which only happens once. What I want to do is use a CGPointMake right when the animation is finished being called. Note that before the deathAnimation is called, there is another animation that is constantly being called 30 times a second. I'm not using anything like cocos2d.

if (enemy1health <= 0) {
    [self slime1DeathAnimation];
    //How can i detect the end of this animation
}

This is how the animation is done:

-(void)slime1DeathAnimation{
    enemy1.animationImages = [[NSArray alloc] initWithObjects:
                              [UIImage imageNamed:@"Slime Death 1.png"],
                              [UIImage imageNamed:@"Slime Death 2.png"],
                              [UIImage imageNamed:@"Slime Death 3.png"],
                              [UIImage imageNamed:@"Slime Death 4.png"],
                              [UIImage imageNamed:@"Slime Death 5.png"],
                              nil];
    enemy1.animationDuration = 0.5;
    enemy1.animationRepeatCount = 1;
    [enemy1 startAnimating];
}

If you need more code just ask


texts: How can I load .obj files in the Soya3D engine?

texts:
I recently found Soya3D, and I want to import .obj files, but it seems to only accept .data files.  How can I import .obj files into Soya3D?

Importing a .obj file named "house" produces this error:

  Traceback (most recent call last):
   File "introduction.py", line 7, in
    model = soya.Model.get("house")
   File "/usr/lib/pymodules/python2.6/soya/init.py", line 259, in get
    return klass._alls.get(filename) or klass._alls.setdefault(filename, klass.load(filename))
   File "/usr/lib/pymodules/python2.6/soya/init.py", line 268, in load
    dirname  = klass._get_directory_for_loading_and_check_export(filename)
   File "/usr/lib/pymodules/python2.6/soya/init.py", line 194, in _get_directory_for_loading_and_check_export
    dirname = klass._get_directory_for_loading(filename, ext)
   File "/usr/lib/pymodules/python2.6/soya/init.py", line 171, in _get_directory_for_loading
    raise ValueError("Cannot find a %s named %s!" % (klass, filename))
  ValueError: Cannot find a  named house!
  * Soya3D * Quit...


texts: How should renderer class relate to the class it renders?

texts:
I am working on making a Pong clone as a practice project. I have a PongState class with members like Ball, Paddle, Board and Score. I want to structure my code so that each object doesn't have to know how to render itself, but a PaddleRenderer class will. I also want to create a PongStateRenderer class, which may use other classes like PaddleRenderer, as well.

How should I let PongStateRenderer know about the internals of PongState so that it can render it? The Ball object in PongState know's it's own position and size, does that mean Ball has to be a public member variable so that PongStateRenderer can also know the position, or is there a better way to do this without totally breaking encapsulation? Perhaps my architecture is totally wrong, and I should use a different method?

I'm working in C# as it says in the tag but a general answer that applies to many languages could also be helpful.


texts: The game I'm working on is very simple. It's a top down scroller. The camera never moves in any way, and all of the objects are in the same location on the Z axis. Since it's a bullet hell game, there are a lot of models on the screen at any given time. That being said, when I call RenderTarget2D, should I set mipmaps to true or false? I haven't noticed any difference at all so far either way.


texts: Asymetrcal Public Key (Host it on a server or distribute with launcher)?

texts: I am currently building a launcher for the front end of my game and I am wondering if I should host the public key on a server and have the launcher pull the data as and when needed, or should I distribute it packaged with the launcher. My thinking is that if I distribute it I will need to update the launcher should I need to change the keys but if I host it then I won't need to I just need to swap the keys on the server. I ask because I am unsure if this would dramatically increase load/traffic on the site should the game become popular.


texts: How can I create a curved path for a ball?

texts:
I am creating a soccer game. Now I want to shoot the ball and create an after-effect resulting in a curved path. I tried several things, but nothing seems to work.

I am using a 3D tool, but the camera is from the top. I especially want to create a curve of the ball with the effect to the left or right.

What is the best way to create a effect on the ball?


texts: Simulate wind affecting a boat using a 2D physics engine like Box2D or SpriteKit?

texts:
I'm looking for a way to simulate the forces created by wind and how it affects a boat.

In a nutshell: if wind hits a boat (sailing yacht), the bow is aligning with the wind and if the wind is strong enough, the boat will then slowly start to move.

I am not looking for a correct simulation of sails or alike. Just wind as it would affect a boat during maneuvers at slow speed.

Here's what I have tried:

Make the boat just one body and apply a force: this does not take into account the heavier stern versus the lighter bow.
Make the stern a heavy body and the bow a lighter one and connect them with a fixed joint: this will make the boat rotate if the same force is applied to both bodies but ignores the fact that once the boat is aligned with the wind, the force should be reduced.
Create many (thousands) of very small objects with little mass and apply a force to them, simulating the wind "particles" and let them hit the boat: this kills performance on slower devices.

Maybe I am missing a very simple solution that would work good enough?


texts: When would I use "scripts" or "scripting" in a game, as opposed to the core language?

texts: The terms scripts and scripting appear to be used interchangeably on the Game Development Stack Exchange, but other than reading questions about a scripting language choice, I don't understand the relationship between scripts and scripting, and the core language. What does a script typically do, when would it be used, and are scripts in some contexts (as defined by game programmers) different than a scripting language?


texts:
I am making a small game where the player is constantly moving upwards, and I am having slight problems with the movement to the sides.
The script located under works quite perfectly in itself, but my problem is that I want the balloon-player to nudge in a direction, rather than go at a constant speed. Kinda like a small punch to the side of the balloon.

How could I easily implement this? GetMouseButton or GetMouseButtonDown?
Thanks in advance. :)

    void Update () {

    transform.Translate(Vector3.up * Time.deltaTime, Space.World);

    if(Input.GetMouseButton(0))
        transform.Translate(Vector3.left * Time.deltaTime, Space.World);

    if(Input.GetMouseButton(1))
        transform.Translate(Vector3.right * Time.deltaTime, Space.World);

}


texts:
I'm trying to learn DirectX and SlimDX but I'm having a terrible time getting started.

I'm taking the Triangle tutorial and trying to add color and transformations.

Starting with controlling color, I've updated the .fx file to the following:

cbuffer cbPerObject
{
    float4x4 gWVP;
};

struct vsInput
{
    float4 positionLS   : POSITION;
    float4 color        : COLOR;
};

struct vsOutput
{
    float4 positionCS   : POSITION;
    float4 color        : COLOR;
};

struct psInput
{
    float4 positionCS   : POSITION;
    float4 color        : COLOR;
};

vsOutput VShader(vsInput input)
{
    vsOutput output;

    output.positionCS = input.positionLS; //mul(position, gWVP);
    output.color = input.color;

    return output;
}

float4 PShader(psInput input) : SV_TARGET
{
    return input.color;
}

And the code updates limited to the following lines:

// create test vertex data, making sure to rewind the stream afterward
var vertices = new DataStream(16 * 6, true, true);
vertices.Write(new Vector4(0.0f, 0.5f, 0.5f, 1f));  // What is W (of POSITION)
vertices.Write(new Color4(.8f, 1f, 0f, 0f));        // What should it's value be?
vertices.Write(new Vector4(0.5f, -0.5f, 0.5f, 1f));
vertices.Write(new Color4(.8f, 0f, 1f, 0f));
vertices.Write(new Vector4(-0.5f, -0.5f, 0.5f, 1f));
vertices.Write(new Color4(.8f, 0f, 0f, 1f));
vertices.Position = 0;

// create the vertex layout and buffer
// Thanks to Mārtiņš Možeiko for fixing these next lines
var elements = new[] {
    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0)
};

var layout = new InputLayout(device, inputSignature, elements);
var vertexBuffer = new SlimDX.Direct3D11.Buffer(device,
    vertices,
    (int)vertices.Length,
    ResourceUsage.Default,
    BindFlags.VertexBuffer,
    CpuAccessFlags.None,
    ResourceOptionFlags.None,
    0);

After a few other attempts at using SV_POSITION, COLOR, and SV_TARGET in the wrong spots, it finally executes without error; however, the triangle does not appear.

Please help me get the triangle working again with this updated shader.
Sample code for SetConstantBuffer() for populating gWVP for standard perspective.

Thanks!


texts: How do I handle game lag due to background apps

texts:
I'm developing a game using libgdx and have noticed on several occasions that other background apps running can cause lag in my game - especially when those apps are being updated in the background. I'm talking serious lag like from 50-60 fps down to under 10 fps while the other app installs.

How should I handle this very noticeable lag?

Thanks!


texts:
I'm making a game with an endless mode where you have to dodge asteroids until you eventually die. Since the game could be endless, I wanted to avoid the coordinates issue mentioned here.

My player ship remains at 0,0,0. The asteroids spawn at the top of the screen and "fall" to simulate the player flying past them. The player can also accelerate and decelerate. I have tried scripting asteroid movement, but now I would like to try using Unity's physics to simplify code.

When accelerating/decelerating I could add force to all existing asteroids, but then asteroids which haven't spawned yet will not reflect the player's current speed. I basically want all asteroids to have the same speed.

I was thinking maybe I could create a dummy physics object that I can apply forces to, that also keeps track of its speed. It would be great if all objects could just reference this dummy object's speed and forces. Is something like this possible with Unity's physics? Or is there a better way to do what I'm attempting?


texts: If I don't use PrefabUtility class, how can I save my changed prefabs and build without exception?

texts:
I'm designing a racing game for my graduation project.
I used PrefabUtility.SaveAsPrefabAsset to save my color change on the car prefabs, I finished the codes and it work well in Unity, but when I want to build my project,the Unity give me a error:The name 'PrefabUtility' does not exist in the current context.
I want to know can I not use PrefabUtility or UnityEditor to save my changed prefabs in assets directory, or are there someways to solve this problem?


texts: Show the tooltip when mouse over at the object unity3d

texts:
i wanted to show the tooltip like this when the mouse over at the object, here is the example image:

and

i already tried this below code, but the message on the debug.log didn't showed up when i am hovering my mouse to the object, the object i give the name same like this:

void Update()
{

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    RaycastHit hit;

    if (Physics.Raycast(ray,out hit) && hit.collider.gameObject.name == "Yify")
    {

        Debug.Log("Yify");

    }

}

And here is my object (i use List to multiple the objects and each object i gave the name), (The object's name "Yify" is on the right side, dark green color):

Please help. Thank you!

Update:

i already got the script that hold movement and attack logic like the image that shown below sir @Korchkidu:


texts:
I'm trying to implement anti-aliasing into a raytracer with super-sampling.

What exactly is adaptive super sampling? I'm picturing it as just sampling all of the pixels which are on the edge of each object. Is that a correct explanation?

Also, is adaptive super sampling a type of MSAA? To my understanding, MSAA is essentially an anti-alising process that does not sample every pixel more than needed/is adaptive.


texts: How do I get to ModPE to perform a function the first time a mod is opened?

texts: I am making a Minecraft PE mod and I want to set a variable only on the first launch of the mod. So, how do I make it it set the variable and then not set it again until I import the mod again?


texts:
Let's say the game we're talking about is some kind of platformer. With all the puzzles, mini-challenges and mechanics aspects it is very, very important to have good control over the character. A single mistake can lead to character death or some other unwanted result.

In some scenes complete control is the key to the victory. Quickly the player becomes involved in the process and every lag or mistake in input processing brings negative experience.

But what if loss of control is needed as a 'feature', it is intended? How can I prevent the players from raging about 'broken gamepad' or 'stupid buggy game'? I want the player to not only understand that it's intended, but also be somewhat happy with it, but can't find a way to show it the right way.

In other games I've seen two types of control loss so far:

Character is unable to do anything, unless animation sequence ends
Character executes some moves without player intervention (like cutscenes or end of stage, when character goes out the screen and you can't stop this).


texts: What´s wrong with my Frustum Culling implementation?

texts:
I´m struggling with a weird problem since hours.
Ive implemented frustum culling with the help of online articles and a book.
The problem is that the objects are not culled correctly.
I´m using Spheres, they are scaled correctly - I just dont know what´s wrong!

Ill just show you some code:

First my frustum is just an array of six planes, and a plane is just a Vector4 with x,y,z and w!

Check if sphere is inside frustum. Maybe the problem lies here:

bool Frustum::checkSphere(const PrimitiveSphere& sphere, const WorldPoint& were) const noexcept {

    const auto pos = were.position + sphere.center;
    for (const auto& plane : planes) {

        const float radius = sphere.radius * were.scale.unitMagnitude(); //unit magnitude is just x + y + z / 3
        const float dist =
            plane.x * pos.x +
            plane.y * pos.y +
            plane.z * pos.z + plane.w;
        if (dist < -radius)
            return false;
    }
    return true;
}

Build my frustum each frame from ViewProjectionMatrix

void Frustum::fromViewProj(const float* const vp) noexcept {

    const float xw = vp[3];
    const float yw = vp[7];
    const float zw = vp[11];
    const float ww = vp[15];

    const float xz = vp[2];
    const float yz = vp[6];
    const float zz = vp[10];
    const float wz = vp[14];

    PrimitivePlane& near = planes[0];
    PrimitivePlane& far = planes[1];
    PrimitivePlane& left = planes[2];
    PrimitivePlane& right = planes[3];
    PrimitivePlane& top = planes[4];
    PrimitivePlane& bottom = planes[5];

    near.x = xw - xz;
    near.y = yw - yz;
    near.z = zw - zz;
    near.w = ww - wz;

    far.x = xw + xz;
    far.y = yw + yz;
    far.z = zw + zz;
    far.w = ww + wz;

    const float xx = vp[0];
    const float yx = vp[4];
    const float zx = vp[8];
    const float wx = vp[12];

    left.x = xw - xx;
    left.y = yw - yx;
    left.z = zw - zx;
    left.w = ww - wx;

    right.x = xw + xx;
    right.y = yw + yx;
    right.z = zw + zx;
    right.w = ww + wx;

    const float xy = vp[1];
    const float yy = vp[5];
    const float zy = vp[9];
    const float wy = vp[13];

    top.x = xw + xy;
    top.y = yw + yy;
    top.z = zw + zy;
    top.w = ww + wy;

    bottom.x = xw - xy;
    bottom.y = yw - yy;
    bottom.z = zw - zy;
    bottom.w = ww - wy;

    for (auto& plane : planes)
        plane.normalize();
}

Now the problem is,
the draw calls are the same if all the orbs are in my frustum or only 5.
But when I rotate my camera slowly a bit the drawcalls are decreasing a bit.
WTF? Just look for yourself (the red rect marks the drawcalls):

Does anybody have an idea what it could be? Or is my code okay and the problem is somewere else? :/


texts: Is it more efficient to add scripts to each GameObject or to a single parent object?

texts: Does a C# script added to a parent object work more efficiently and effectively (in terms of both memory and performance) on all objects, in my case lighting, or adding script components to each lighting/GameObject object? This goes for other GameObjects parented in the hierarchy.


texts: Using Box2D in LibGDX, is there a reason a fixture set to be a sensor would only -sometimes- detect a collision?

texts:
I am working on a 2D game in LibGDX. Currently, I am testing interactions between a player's weapon and enemies - in particular, a sword and an enemy monster.

The player has a hurtbox and the sword has a hitbox. The player's hitbox and hurtbox are filtered so that they do not interact with each other. However, the p
layer's hitbox and hurtbox are supposed to interact with the monster. However, a collision between the sword and the monster is only registered sometimes - specifically, four times when I launch the application, and then no more collisions will register. However, if the player bumps into the monster so that the monster gains some velocity, collisions will register again until the enemy stops moving.

Is there a reason for this / is there a pattern here for when collisions are registering and when they're not that I'm missing?

Note: I have tried both creating the hitbox only when the player is attacking, and having the hitbox be inactive until the player is attacking, then making it active, then setting it to be inactive again. Both cases result in the same failure to register all collisions.

This is the general code for the creation of the hitbox fixture:

    CircleShape shape = new CircleShape();
    shape.setRadius(25f * Constants.MPP);
    shape.setPosition(new Vector2(0f, 0f).scl(Constants.MPP));

    FixtureDef fixture = new FixtureDef();
    fixture.filter.categoryBits = Constants.CATEGORY_PLAYER_WEAPON;
    fixture.filter.maskBits = (short) (Constants.CATEGORY_MONSTER);
    fixture.isSensor = true;
    fixture.shape = shape;
    f = hitbox.createFixture(fHitbox);

    hitboxShape.dispose();

Thanks in advance!


texts: What is billboarding, and can/should it be used in 3D games to create special effects for weapon blasting effects?

texts: What is billboarding, and can or should it be used to create special effects for 3D games on weapon blasting effects?


texts: Imported Blender modular mesh lighting/shadows issue - Unity

texts:
Hi I've very recently started using Unity and am creating a game level. I've created my environment in blender and am currently using a modular design as I'd like to include destructible environments.

I've applied test textures and colours to the mesh but have noticed problems when importing into unity.

In blender the lighting appears to cast shadows smoothly across the modular design, but once imported into unity I get random "light spots" and consecutive pieces appear slightly different shades in places.

Each module of a particular type shares a linked material and texture.

I've attached the Blender render first and then the Unity render (they have different lighting as I haven't added all the lights to blender, but the difference is obvious)

The walls are made up of cuboids 2.4 x 1.0 x 0.15

And the floors 1.0 x 1.0 x 0.1

It seems that some of the 'pieces' are receiving/casting shadows differently.


texts: How should I set up 2D animations for weapons in Unity?

texts:
I have a character composed of several sprites (legs, torso, head, arms). The character has the ability to pick up weapons, which are of varied types.

Each type of weapon has its own animation (sprite sheet). Ideally I want the weapons not only to animate themselves, but also affect how the player is animated (e.g. lean back when swinging sword).

Here's how I'm thinking of setting it up right now:

Player has an animator controller with states for Walking, Attacking, Idle, Flinching and this controls all the body parts.

Main questions:
- How can I incorporate jumping in this?
- How can the weapon animations have control over the rest of the body?

For having different weapons I am thinking of adding different states per weapon type, but I don't think that's a great way, especially when I start adding combos.


texts: Correct order of entity updates and collision detection

texts:
I'm trying to simulate a number of units walking in a single file. My update loop looks like this:

for each unit:
    n = compute next position
    if n is empty then move to n

If I start the loop from the foremost unit, it moves first and leaves its current position to the unit behind it. When the loop finishes every unit will be moved one step. However if I start the loop from some other unit, it can't move since its next position is occupied by the unit in front of him. So, in the worst case it would take n-1 ticks for a unit to move one step (where n is the number of units in front of it).

I tried changing my update like this:

for each unit:
    save current position to p
    n = compute next position
    move to n

detect colliding units and move them back to their p positions

In this case the units move fine, as long as we have a single group. But another problem arises when the group collides head-first into another group. In this case, the foremost units will collide and they need to be moved back, but their previous positions will be occupied (by the units behind them) and they also need be moved back. This method also needs too many iterations.

How do RTS games tackle this problem? Is there a standard approach?


texts:
I don't understand the meaning of the term "2.5D." I'm specifically confused about the difference between 2.5D and 3D environments, even though I've read different definitions and articles about both. I understand the parts where 2.5D is like 3D but I don't get the parts where 2.5D is different.

So, what does it mean for a game to be 2.5D? For example, is the game shown here 2.5D?


texts: Google Play Games Signs Out Automatically without Internet Unity

texts:
I am using this in my game to implement games saving and loading.
I have also tried the basic sign in process by using the following start function :-

{

        PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ()
        // enables saving game progress.
        .EnableSavedGames ()
        .Build ();

        PlayGamesPlatform.InitializeInstance (config);
        // recommended for debugging:
        PlayGamesPlatform.DebugLogEnabled = true;
        // Activate the Google Play Games platform
        PlayGamesPlatform.Activate ();

        Social.localUser.Authenticate ((bool success) => {
            if (success){
                MyAutoSave.isLoaded = false;
            }
        });
    }

}`

I can sign in on google play games without any issues. Soon after that if I quit the game and start again without data connection, it gets authenticated without any issue.
If my data connection remains off for say more than an hour, and I start the game without Internet connection, there is no authentication whatsoever. If I close the game and start again soon after that, it gives me that google play games sign in popup. So what i can conclude is that it signs out automatically after some time if there is no Internet available. Is there any fix for this.?
Thanks


texts:
So in my most recent 2D game I draw objects like so.

  _spriteBatch.Draw(_sprite, Center(), null, Color.White, _rotation, new Vector2(_sprite.Width / 2, _sprite.Height / 2), _scale, SpriteEffects.None, 0);

My bounding boxes are generated using a two step algorithm where I make the transform matrix, then apply it to a Rectangle of the sprite's height and width.

    public Rectangle BoundingBoxTransformed
    {
        get
        {
            //Center and rotate our Rectangle

            Matrix m = Matrix.CreateScale(_scale) *
                Matrix.CreateTranslation(new Vector3(new Vector2((float)-BoundingBox.Width / 2, (float)-BoundingBox.Height / 2), 0.0f)) *
                Matrix.CreateRotationZ(_rotation) *
            //Move our rectangle toward the player, then recenter it by undoing the original translation (now that it's already rotated)

                Matrix.CreateTranslation(new Vector3(_location, 0.0f)) * Matrix.CreateTranslation(new Vector3((float)BoundingBox.Width / 2, (float)BoundingBox.Height / 2, 0.0f));
            return CalculateBoundingRectangle(new Rectangle(0, 0, _sprite.Width, _sprite.Height), m);
        }
    }

This is how I've been finding the new sizes for the scaled bounding boxes.

   public static Rectangle CalculateBoundingRectangle(Rectangle rectangle,
                                                       Matrix transform)
    {
        // Get all four corners in local space
        Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
        Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
        Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
        Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);
        // Transform all four corners into work space
        Vector2.Transform(ref leftTop, ref transform, out leftTop);
        Vector2.Transform(ref rightTop, ref transform, out rightTop);
        Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
        Vector2.Transform(ref rightBottom, ref transform, out rightBottom);
        // Find the minimum and maximum extents of the rectangle in world space
        Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
                                  Vector2.Min(leftBottom, rightBottom));
        Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
                                  Vector2.Max(leftBottom, rightBottom));
        // Return that as a rectangle
        return new Rectangle((int)min.X, (int)min.Y,
                             (int)(max.X - min.X), (int)(max.Y - min.Y));
    }

I thought that I had the transformations all figured out, but when I run the game, I can see that my bounding boxes do not match up with my sprites.

So what is it that's going on here? Are my transformations out of order? Quick edit: The purple boxes are the original bounding boxes, which are used to determine the height and width of the red (transformed, i.e. scaled and rotated) bounding boxes.


texts:
In my game, If i click on terrain my soldier goes there. In my terrain there is no place without a navmesh. So, I want to make area where player moves his soldiers on it. If he clicks outside this area, soldier will not move there or moves to closest point inside the area to this outside. Could invisible wall do this ?
Image.Image2.
update:
To solve this, make any object fit your area. then, use mouse to detect that object.


texts: How to render alpha channeled animated 2D sprites in OpenGL ES 2.0

texts:
I searched, but I can't find specifically how to render animated 2D sprites with an alpha channel onto a 3D polygon, z=0, in OpenGL ES 2.0.

This is just a basic 2D concept, but since I'm using, OpenGL ES 2.0, I need to use 3D vertex data to render to the viewport. I'm also assuming I'll need a 0.01 like z-depth projection matrix.

I don't know if I load parts of the bitmap first onto the texture data, or just use a large texture and manipulate the UV onto the 2D/3D vertices? Should it all be done in a shader?, if so, how would that be done (using uniforms and attributes in a shader)? What is the best technique for this? When do I update the animation as well, in the draw function or a separate update function?


texts: Best way of writing pixel manipuliting-intensive applications with OpenGL/Direct3D

texts:
Recently I have been making little experiments with engines similar to old Wolfenstein 3D, Doom and Build, engines where the 3D rendering is entirely done in software and therefore you need full access to the screen buffers at pixel level.

In the days of DOS and before we had current GPUs it was relatively straightforward to get a surface to plot pixels. You had to devise the fastest way to do your calculations and the fastest way of updating the framebuffer. In fact, it is still possible by using libraries like SDL, which still give you a reasonable speed when you manipulate surfaces at pixel level.

So I wonder which would be the best way of dealing with pixel-intensive applications like the ones I suggest using current GPUs, by using OpenGL or Direct3D.

I understand this sounds absurd, but I have been looking at API documentation and it seems that it is a feature that we have somewhat lost in current hardware. I see suggestions as using glDrawPixels or using pixel shaders, but no solid explanation or theory which can help me to make the right decisions.


texts: I have 2 rectangles and I want to know if its a length collision or a breadth collision. I will also need to know the rectangle that's acting as pivot. I have made a small illustration. Here, V2 is the pivoting rectangle.


texts: How do I make an image appear based on the current state I'm in?

texts:
I am following a tutorial called Complete C# Unity Developer 2D: Learn to Code Making Games.  In one section we create a text-based game, where we display a canvas with some UI elements to the user.  The text changes based on the current state, which is setup through a couple of scripts.  Just for future knowledge (it isn't part of the tutorial), I want to make an image display for each state.

Before I post the scripts, here is what I have tried: 1) I serialized a Sprite field in one of the scripts so that I could assign a .jpg asset sprite to it.  At that point I was not sure how to get it to appear based on the state, which is an array of states.  2) I created a UI Image and added it to the canvas, then disabled it.  My intent here was to enable it when the state.name == x.  Unfortunately, I can't seem to get that to work either.

I am using two scripts, 1) AdventureGame.cs & 2) State.cs:

1) AdventureGame.cs

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

public class AdventureGame : MonoBehaviour
{
    [SerializeField]
    Text m_textComponent;
    [SerializeField]
    State startingState;
    // I added this Sprite field
    [SerializeField]
    Sprite m_spriteComponent;

    State state;

    void Start()
    {
        state = startingState;
        m_textComponent.text = state.GetStateStory();
        // This is what I added, a call to a method in the other script
        m_spriteComponent = state.GetStateSprite();
        Debug.Log(m_spriteComponent);
        // The sprite is called HellDoor
    }

    void Update()
    {
        ManageState();
    }

    private void ManageState()
    {
        var nextStates = state.GetNextStates();
        for (int index = 0; index < nextStates.Length; index++)
        {
            if (Input.GetKeyDown(KeyCode.Alpha1 + index))
            {
                state = nextStates[index];
            }
            m_textComponent.text = state.GetStateStory();

        }
        // Tested for state name to be sure, Door is one of them

        Debug.Log(state.name);
        if (state.name == "Door")
        {
            // Not sure what to put here
        }

    }

}

2) State.cs

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

// Creates a new slot called State in the Create menu!
[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject
{
    // First number determines minimum size of the field, and the second number
    // determines the amount of lines before you start to scroll
    [TextArea(10, 14)]
    [SerializeField]
    string m_storyText;
    [SerializeField]
    State[] nextStates;
    // This is the field I added
    [SerializeField]
    Sprite m_stateSprite;

    public string GetStateStory()
    {
        return m_storyText;
    }

    public State[] GetNextStates()
    {
        return nextStates;
    }
    // This is the method I added
    public Sprite GetStateSprite()
    {
        return m_stateSprite;
    }
}

Additionally, this is what I have setup in the editor.


texts: How to customize a character with new objects (clothes, body parts) in a 3D game?

texts:
how do we customize a character in a game by adding, for example, a different clothing? The character has an armature, made in Blender, if I add a new object with the game engine, I would have to copy the position for each frame, and the orientation?
Or is there a technique to make the model in Blender with different meshes, find the meshes in the .dae file (for scenekit, but it might be the same for fbx for unity), and replace it with a new object, and the orientation will be automatically copied?

Has anyone had some experience with this?

Thanks


texts:
I am a beginner in Slick2D.
I used TiledMap render in my game,but I do not know why it  use 15%cpu and how to fix it.
I used map is 1024*768.
This is a part of my code.
Thanks for any help

 public class Map{
        public static Image[][] solids;
        public static int WIDTH;
        public static int HEIGHT;
        private static TiledMap map;
        private static int objectLayer;
        private static int mapEndX;
        private static int mapEndY;
        private static int  startX=0,realX=0;
        private static int  startY=0,realY=0;
        public static void render(){

            map.render(startX, startY);
        //  map.render(startX, startY, startX+60, startY+60, 80, 80);
        }

        public static void update(){

            map.getTileId(0, 0, objectLayer);
        }

        public static void load(String name){

            map=Resources.getMap(name);
            objectLayer = map.getLayerIndex("solids");
        }

        public static void setStartXY(int tileX,int tileY){
            startX = (-1 * tileX * Tile.SMALL_SIZE);
            realX = ( -1 * startX);
            startY = (-1 * tileY * Tile.SMALL_SIZE);
            realY = ( -1 * startY);
            mapEndX = (startX + map.getWidth() * Tile.SMALL_SIZE);
            mapEndY = (startY + map.getWidth() * Tile.SMALL_SIZE);

        }

        public static boolean hitTest(int x,int y){

        /*  if((map.getTileId((x+startX)/4-1, (y+startY)/4-1,objectLayer) ==0)){
                return true;
            }*/
            return false;
        }

    }

//----------------------------------------------

 public class  Play extends BasicGameState{
         int x=0,i=100,j=50;
         int y=0;
         private ArrayList<Entity> entities;
         private TiledMap map;
         Image image;
        public Play(int play) {

        }

        @Override
        public void init(GameContainer gc, StateBasedGame arg1) throws SlickException {
            try {
                    Map.load("test");
                    Map.setStartXY(0, 0);
                } catch (Exception e) {

                    e.printStackTrace();
                }

            entities = new ArrayList<Entity>();
            entities.add(new Player());
            System.out.println("1");

        }

        @Override
        public void render(GameContainer gc, StateBasedGame arg1, Graphics g) throws SlickException {

            g.setBackground(Color.black);
        //  g.scale(4f, 4f);
            Map.render();

            for(int i=0;i < entities.size();i++){

                entities.get(i).render(gc, g);
            }
        }

        @Override
        public void update(GameContainer gc, StateBasedGame sbd, int delta) throws SlickException {
            for(int i=0;i < entities.size();i++)
            {
                try {
                    entities.get(i).update(gc, delta);
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
            Map.update();

        }

        @Override
        public int getID() {

            return state.Play;
        }

     }


texts: Why does my VertexDeclaration apparently not contain Position0?

texts:
I'm trying to get my code from calling each individual draw call down to using at least a VertexBuffer, and preferably an indexBuffer, but now that I'm attempting to test my code, I'm getting the error:

  The current vertex declaration does not include all the elements required by the current vertex shader. Position0 is missing.

Which makes absolutely no sense to me, as my VertexDeclaration is:

public readonly static VertexDeclaration VertexDeclaration
    = new VertexDeclaration(
        new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement(sizeof(float) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0),
        new VertexElement(sizeof(float) * 3 + 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0)
        );

Which clearly contains the information.
I am attempting to draw with the following lines:

VertexBuffer vb = new VertexBuffer(GraphicsDevice, VertexPositionColorNormal.VertexDeclaration, c.VertexList.Count, BufferUsage.WriteOnly);
IndexBuffer ib = new IndexBuffer(GraphicsDevice, typeof(int), c.IndexList.Count, BufferUsage.WriteOnly);

vb.SetData<VertexPositionColorNormal>(c.VertexList.ToArray());
ib.SetData<int>(c.IndexList.ToArray());

GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vb.VertexCount, 0, c.IndexList.Count/3);

Where c is a Chunk class containing an 8x8x8 array of boxes.

Full code is available at https://github.com/mrbaggins/Box/tree/ProperMeshing/box/box.

Relevant locations are Chunk.cs (Contains the VertexDeclaration) and Game1.cs (Draw() is in Lines 230-250). Not much else of relevance to this problem anywhere else. Note that large commented sections are from old version of drawing.

EDIT:
I condensed the problem down even further, the following draw code won't even run, with the same error:

VertexBuffer vb = new VertexBuffer(GraphicsDevice, VertexPositionColor.VertexDeclaration, 3, BufferUsage.WriteOnly);
VertexPositionColor[] temp = {
            new VertexPositionColor(new Vector3(-3.0f,-3.0f,3.0f), Color.Blue),
            new VertexPositionColor(new Vector3(0.0f,0.0f,0.0f), Color.Blue),
            new VertexPositionColor(new Vector3(1.0f,1.0f,1.0f), Color.Blue) };

vb.SetData<VertexPositionColor>(temp);
GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);


texts:
I am wondering about how time manipulation mechanisms in games are typically designed. I am particularly interested in time reversing (sort of like in the latest SSX or Prince of Persia).

The game is a 2D top down shooter.

The mechanism I am trying to design/implement has the following requirements:

1) Actions of entities apart from the player character are completely deterministic.

The action an entity takes is based on the frames progressed since level start and/or the    position of the player on the screen
Entities are spawned at set time during the level.

2) Time reverse works by reversing back in realtime.

Player actions are also reversed, it replays in reverse what the player performed. Player has no control during reverse time.
There is no limit on the time spent reversing, we can reverse all the way to the beginning of the level if wanted.

As an example:

Frames 0-50:
Player moves foward 20 units over this time
Enemy 1 spawns at frame 20
Enemy 1 moves left 10 units during frame 30-40
Player shoots bullet at frame 45
Bullet travels 5 foward (45-50) and kills Enemy 1 at frame 50

Reversing this would play back in realtime:
Player moves backwards 20 units during this time
Enemy 1 revives at frame 50
Bullet reappears at frame 50
Bullet moves backwards 5 and disappears (50-45)
Enemy moves left 10 (40-30)
Enemy removed at frame 20.

Just looking at movement I had some ideas about how to achieve this, I thought of having a interface that changed behavior for when time was advancing or reversing. Instead of doing something like this:

void update()
{
    movement += new Vector(0,5);
}

I would do something like this:

public interface movement()
{
    public void move(Vector v, Entity e);
}

public class advance() implements movement
{
    public void move(Vector v, Entity e)
    {
            e.location += v;
    }
}

public class reverse() implements movement
{
    public void move(Vector v, Entity e)
    {
        e.location -= v;
    }
}

public void update()
{
    moveLogic.move(new vector(5,0));
}

However I realised this would not be optimal performance wise and would quickly become complicated for more advance actions (such as smooth movement along curved paths e.t.c.).


texts: Having trouble making game time pause and unpause

texts:
I've been trying to make it where when the player does a certain task, the game's time will pause. When the player does another action, the game's time would unpause and continue. I had my code like so:

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

public class timeScript : MonoBehaviour
{
    //uGUI Items
    public Text date;
    public Text playerCash;

//Times
public static int week;
public static int month;
public static int year = 1980;
//amount of cash
public static int myCash = 10000;
public AlertBox alert;
public Text timeText;

bool timeActive = true;
int time;

int day;

void Start()
{
    InvokeRepeating("Timer", 0, 1);
}

public static void Timer()
{
    timeText.GetComponent<Text>().text = "W" + week.ToString() + "" + year.ToString();

    playerCash.GetComponent<Text>().text = "$" + myCash.ToString();

    #region YEAR
    //Check if month equals 13 (allows for 12th month to be counted)
    if (month == 13)
    {
        year++;
        month = 0;
    }
    #endregion
    #region MONTH
    //Check if week equals 5 (allows for 5th week to be counted)
    if (month == 5)
    {
        month++;
        week = 0;
    }
    #endregion
    #region WEEK
    //Check if day equals 8 (allows for 7th day to be counted)
    if (day == 8)
    {
        week++;
        day = 0;
    }
    #endregion
    #region DAY
    //Check if Time equals 5 (allows for 4 seconds)
    if (time == 2)
    {
        day++;
        time = 0;
    }
    else
    {
        time++;
    }
    #endregion

I tried using CancelInvoke(timeScript.Timer()); in another c# file but all it did was give me an error that stated I couldn't convert from string to void.


texts: How to get the MonoGame Templates working with Visual Studio C# 2013 Express?

texts:
I've been looking around forever, and I can't seem to find a way to install the MonoGame C# Templates for Visual Studio 2013 Express. These include things like "SpriteFont", etc. that pop up in the templates menu when you click "Add New Item" in the solution menu. I've installed every last MonoGame related thing I can find on the internet and NOTHING has solved my problem.

To clarify, I have all the project templates that come with MonoGame:

but I'm missing all the item templates:

There should be templates in the list there labelled "SpriteFont" and other miscellaneous MonoGame related templates.

So how do I get the MonoGame templates?

EDIT: For the record, I have already tried following the advice given here, here, here, here, here and here. I also learnt from the 5th link that apparently I don't have the MonoGame template projects for things like "Empty Content Project" either.

EDIT 2: This didn't work either.

EDIT 3: I've also followed the advice here, yet again to no avail (what a surprise!).


texts:
When creating an android game for example space invaders. How big would the sprites have to be? The Enemy ships and player ship and boss ships. So they fit on the android phone and is playable. I'm confused between resolution and this.

Thanks.


texts: Help understanding Accidental Noise Gradient function

texts:
Background:

I am trying to create a set of functions to manipulate noise, similar to Libnoise, Fastnoise and the Accidental Noise Library. The end goal is to produce terrain.

As recommended by this article (http://accidentalnoise.sourceforge.net/minecraftworlds.html) I am starting out with a 'Gradient' function.  Quoting the author:

  The Gradient function is given a line-segment in N-dimensional space
  (ie, in whatever coordinate space we are working in, be it 2D, 3D, or
  higher) and calculates a gradient field aligned along this segment.
  Input coordinates are projected on this line, and their gradient value
  is calculated depending where on the line they lie in relation to the
  endpoints of the defining segment.

Even after repeatedly reading the article and looking at these two other questions I found (2D Terra(ria)in generation - Accidental noise and Accidental noise - Gradient function) I'm still having problems understanding exactly what the function is doing.

Questions:

My test chunk is of size 32x32x32 and ranges from -16 to +16 on the x, y and z axis.  In this case, would the inputs to the function be x/32, y/32, z/32?
Does the function map points between 0 and 1 (as input) to a point between 1 and -1 (as output)? I.e if my x, y and z where -16, -16, -16, would I get 1, 1, 1 back?
Why in the extract below is the line segment (0,1)->(0,0) rather than (0,0)->(0,1)?  Given that the example line segment is defined as x1=0, x2=0, y1=0, y2=1.

  The Gradient function accepts a line segment in the form of (x1,x2,
  y1,y2) for the 2D case, extended to (x1,x2, y1,y2, z1,z2) for the 3D
  case. The point formed by (x1,y1) delineates the start of the line
  segment, which is mapped to 0. The point formed by (x2,y2) is the end
  of the line segment that maps to 1. So here we are mapping the line segment (0,1)->(0,0) to the gradient.

Any help on this would be greatly appreciated, thanks.