texts: Find the footprint of an isometric entity

texts:
I'm working on making a 2D isometric engine in Java. I'm getting into collision detection and I've hit a bit of a problem.

Characters in-game are not restricted to movement from tile to tile - they move freely. My problem is that I'm not sure how to stop a player from colliding with, say, a crate, without denying them access to the tile.

For instance, say the crate was on .5 of a tile, and then the rest of the crate was off the tile, I'd like the player to be able to move on to the free .5 of the tile instead of the entire tile becoming blocked.

The problem I've hit is that I'm not sure how to approximate the size of the footprint of the object. Using the image's dimensions don't work very well, since the object's "height" in gamespace translates to additional floorspace being taken up by the image.

How should I estimate an object's size? Mind, I don't need pixel-perfect detection. A rhombus would work fine.

I'm happy to provide any code you might need, but this seems like a math issue.


texts: Finding Z given X & Y coordinates on terrain?

texts:
I need to know the most efficient way of finding Z given X & Y coordinates on terrain. My terrain is set up as a grid, each grid block consisting of two triangles which may be flipped in any direction. I want to move game objects smoothly along the floor of the terrain without "stepping." I'm currently using the following method with unexpected results:

double mapClass::getZ(double x, double y)
{
    int vertexIndex = ((floor(y))*width*2)+((floor(x))*2);

    vec3ray ray = {glm::vec3(x, y, 2), glm::vec3(x, y, 0)};

    vec3triangle tri1 = {   glmFrom(vertices[vertexIndex].v1),
                            glmFrom(vertices[vertexIndex].v2),
                            glmFrom(vertices[vertexIndex].v3)   };

    vec3triangle tri2 = {   glmFrom(vertices[vertexIndex+1].v1),
                            glmFrom(vertices[vertexIndex+1].v2),
                            glmFrom(vertices[vertexIndex+1].v3) };

    glm::vec3 intersect;

    if (!intersectRayTriangle(tri1, ray, intersect))
    {
        intersectRayTriangle(tri2, ray, intersect);
    }

    return intersect.z;
}

intersectRayTriangle() and glmFrom() are as follows:

bool intersectRayTriangle(vec3triangle tri, vec3ray ray, glm::vec3 &worldIntersect)
{
    glm::vec3 barycentricIntersect;

    if (glm::intersectLineTriangle(ray.origin, ray.direction, tri.p0, tri.p1, tri.p2, barycentricIntersect))
    {
         // Convert barycentric to world coordinates
        double u, v, w;
        u = barycentricIntersect.x;
        v = barycentricIntersect.y;
        w = 1 - (u+v);

        worldIntersect.x = (u * tri.p0.x + v * tri.p1.x + w * tri.p2.x);
        worldIntersect.y = (u * tri.p0.y + v * tri.p1.y + w * tri.p2.y);
        worldIntersect.z = (u * tri.p0.z + v * tri.p1.z + w * tri.p2.z);
        return true;
    }
    else
    {
        return false;
    }
}

glm::vec3 glmFrom(s_point3f point)
{
    return glm::vec3(point.x, point.y, point.z);
}

My convenience structures are defined as:

struct s_point3f { GLfloat x, y, z; };
struct s_triangle3f { s_point3f v1, v2, v3; };
struct vec3ray { glm::vec3 origin, direction; };
struct vec3triangle { glm::vec3 p0, p1, p2; };

vertices is defined as:

std::vector<s_triangle3f> vertices;

Basically, I'm trying to get the intersect of a ray (which is positioned at the x, and y coordinates specified facing pointing downwards toward the terrain) and one of the two triangles on the grid. getZ() rarely returns anything but 0. Other times, the numbers it generates seem to be completely off. Am I taking the wrong approach? Can anyone see a problem with my code? Any help or critique is appreciated!

EDIT:
After considering what David Cummins has suggested, I can confirm that the ray and the triangle should always be intersecting. I added some debugging code to visualize the data. The area shaded red contains the two triangles, and the blue line is the line/ray being checked for intersection. Depth has been disabled when drawing the line.

Here is an example of data being passed to glm::intersectLineTriangle():

triangle #1:
v1={x=19.0000000 y=34.0000000 z=2.70000005},
v2={x=19.0000000 y=33.0000000 z=2.70000005},
v3={x=18.0000000 y=33.0000000 z=2.70000005}

triangle #2:
v1={x=18.0000000 y=33.0000000 z=2.70000005},
v2={x=18.0000000 y=34.0000000 z=2.70000005},
v3={x=19.0000000 y=34.0000000 z=2.70000005}

ray origin:
{x=18.5000000 y=33.1871414 z=10.0000000}

ray direction:
{x=18.5000000 y=33.1871414 z=-10.0000000}

Despite passing seemingly reasonable arguments, it always returns false. Leaving barycentricIntersect as {x=0.0 y=0.0 z=0.0}. Am I misusing the function? Are the values I am passing invalid, and I'm just blind to it?

EDIT 2:
I've written a quick SSCCE. I would be extremely grateful if someone could help me debug this issue.


texts: How can I generate mesh distance fields at runtime on a procedural mesh in unreal engine 4.26?

texts:
I am building a simulation game that and I that allows the player to create procedural buildings rather than placing static scenery items. If possible, I would like to write a shader that can take the vertices, normals, tangents, etc. and generate an identical mesh distance field so that I can leverage UE4's distance field ambient occlusion and so that various materials can detect generated geometry.
One project that appears to successfully achieve this is the Voxel Plugin. I have looked at the source but I am stumped as to where to start. I failed to find solid resources about this topic online. However, I did find this resource techniques to generate distance fields but this is not clear enough. I Any help is much appreciated. Thank you.


texts: How do I listen for an Admob interstitial ad load event?

texts:
I can show interstitial AdMob ads with the following code:

    if (GUI.Button(new Rect(10, 300, 150, 50), "Load Interstitials"))
    {
        interstitial.LoadAd(interstitialsRequest);
    }

    if (GUI.Button(new Rect(10, 400, 150, 50), "Show Interstitials"))
    {
        if (interstitial.IsLoaded())
        {
            interstitial.Show();
        }
    }

That's all working well.

Now I want to attach a listener for when the interstitial ad has loaded. I checked all the available source files, but can't find the right listener method.

void onAdLoaded()
{
    print("Interstitial Ad Loaded");
}

public void HandleAdLoaded(object sender)
{
    print("HandleAdLoaded event received.");
    // Handle the ad loaded event.
}

I use googleads-mobile-plugins for Admob ads.

What listener should I be using?


texts:
I am attempting to create a server-centric RTS (as opposed to usual parallel synchronised simulation route of most RTS games today) - however I am still leveraging the discreet N-turns-ahead paradigm discussed by one of the AOE developers on Gamasutra.
I have [possibly questionably?] decided that the path finding should only ever find the next cell the entity needs to move to, and was wondering if anyone has any clever ideas on how to optimize the algorithm for this specific scenario - or any other ideas on how to keep the pathfinding as lean as possible on the server.
I have investigated a few possible algorithms but could only come up with one appropriation: Tiered A-Star - Relatively large T1 tiles, work out (and cache) each cell as you enter it. Other than that: doing the full A-Star pass and caching the entire path, which might use too much memory if a large amount of units are present.
I know about the existence of naive progressive pathfinding algorithms (if you hit a block, turn in the direction closer to your target etc.) but they suffer from infinite feedback loops - and very poor pathing even if visited blocks are memorised. Not an option.
Many thanks.


texts: How to clip or mask entity in android/andengine?

texts:
I want to implement masking with sprite in Andengine. I want same functionality as in ios class called

  SKCropNode

which works like an masking node!
Is there any workaround like this in andengine/opengl ?
Thanks.

Edit:
This is something I was trying to mask an entity, got no effect, any suggestion?

public class ClippingEntity extends Entity//BaseSprite
{

protected int mWidth;
protected int mHeight;

public ClippingEntity(float pX, float pY, int pWidth, int pHeight, TextureRegion t)
{
    super(pX, pY);//, pWidth, pHeight, t);
    mWidth = pWidth;
    mHeight = pHeight;
}

@Override
protected void onManagedDraw(GL10 pGL, Camera pCamera)
{

    pGL.glPushMatrix();
    {

        pGL.glEnable(GL10.GL_SCISSOR_TEST);
        pGL.glScissor(0 + (int) mX, 800 - mHeight + (int) mY, mWidth, mHeight);

        super.onManagedDraw(pGL, pCamera);

        pGL.glDisable(GL10.GL_SCISSOR_TEST);

    }
    pGL.glPopMatrix();

}

}

I have also tried Stencil Test but it just clears the color of rectangle. ref: opengl mask tests

Ultimate goal is to disable drawing changes in specific entity where it may aslo have transparent background.


texts: Efficient way to load chunks of a 2d level to prevent game from loading stutters

texts:
I am building a 2D sidescroller game in Unity3D.

It's tile-based. To get better performance I divided the level into chunks. I activate these chunks when the player enters 2D Triggers and deactivate it again when he exits the 2d trigger. So I normally only have a max of 2 chunks loaded.
This works good BUT I do have some loading stutters of a few frames when I load a new chunk. How can I prevent that from happening?

Thank you!


texts: Creating jar file for SFS2X is making issue

texts:
I created a test script to explore Smartfoxserver 2X(SFS 2X). In Eclipse I created 2 classes for math Handler with the SFS plugin. and I export the project as a .jar file. Then I place the jar file in this path \SmartFoxServer_2X\SFS2X\extensions\myExt, then started the server. The server is getting close, It's not working. I checked a lot of tutorials all are using the same method. I don't know what was the issue. If anyone knows please help.
Class 1:
package com.smartFoxServerPracticeOne;
import com.smartfoxserver.v2.extensions.SFSExtension;

public class GameManagerReq extends SFSExtension {
    @Override
    public void init() {
        // TODO Auto-generated method stub
        this.addRequestHandler("math", MathHandler.class);
    }
}

Class 2:
package com.smartFoxServerPracticeOne;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class MathHandler extends BaseClientRequestHandler {

    @Override
    public void handleClientRequest(User player, ISFSObject params) {
        int n1 = params.getInt("n1");
        int n2 = params.getInt("n2");

        ISFSObject rtn = new SFSObject();
        rtn.putInt("sum", n1 + n2);

        GameManagerReq parentEx = (GameManagerReq) getParentExtension();
        parentEx.send("math", rtn, player);
    }
}


texts: How to properly handle the landing part in a jump animation

texts:
Look at this sprite sheet.

It is clear that frame 1-3 are the "jump up" frames after which the last frame will be fixed until the "peak" of the jump (when gravity starts pulling back). When moving back down frame 4-7 are used and it all ends with an "idle" frame (which is not shown here in this jump sprite).

My question is about frame 6 and 7 in this sprite. When the entity "lands" after a jump it is suppose to run animation 6-7 as the "landing" animation. When moving down in a jump frame 4-5 are easy because they are the "start" of the animation. Frame 5 can be kept for as long as you fall... but what is the appropriate way to go from frame 5 to 6-7-x? Do you check if the frame after the next is a fall and then "initiate" landing or do you do that when you have actually hit the ground?

It can't be timed because of various scenarios such as jumping off a cliff or jumping under a low roof hitting your head and bouncing you back down.

Any ideas?


texts: Selling Android apps from Android-Market-unsupported countries

texts:
I am in Latvia (which the Android market doesn't support as a country for selling apps from), and I am thinking about the best way of monetizing my app. So far I've come up with these options:

Pretend I am from a supported country. Get a bank account there, etc.
Use PayPal for in-app purchases. The player gets, say, the first 10 levels for free, but is then asked to pay 0.99$ for the rest of the game. Downside: Players might not feel comfortable entering PayPal details into an app. Android market might not like it either.
Making the app free and earning money through advertising. Let's do some calculation here: Say I get 1M free downloads, each user during his playtime would see 10 banners, so 10m / 1000 * 0.3 is about 33k$ if we use AdMob with their 0.3$ per 1000 impressions. On the other hand, if we use PayPal and in-app purchases, we need a >3% conversion rate to beat this..

What should I do?

Edit: From what I just read all over the net, it looks like advertisers will change their eCPM price a lot without telling you. Using in-app PayPal purchases at least allow you to monitor the cash flow.


texts:
I'm creating a display for a GPS-based embedded system and would like to have an arrow indicating the current bearing. I'd love the arrow to have a 3d appearance by rotating it on a plane tilted up toward the camera, as per these images.

My original idea was to have an ellipse that represents a circle on the tilted plane and plot the bearing angle as a point on the ellipse (this would be the 'head' of the arrow). The rest of the arrow would be drawn by offsetting the bearing by two fixed angles (say 160 and 200 degrees) to make the two points of the tail, then plotting those on the ellipse. The line connecting these two tail points would have its midpoint moved towards the head point to create the arrow shape.

As the target is a bitmap display and I would have to do the rendering myself, is there  an algorithm for rotating a bitmap on an arbitrary plane given an angle of the plane and the angle of rotation? Or is there a better way to plot the arrow as a 3d shape, then translate to 2d?


texts:
I have an formula that generates a number from  20 to 180 (degree).

var a = 20 * Math.pow(str/dist, 1.5));
    a = Math.max(180, w);

Using this formulae, i can generates some arcs and draw them just fine and depending on dist (which is cursor distance from target), the arc is either very wide, or narrow (pow basicly makes it so the arc expands non-linear).

This approach works in one direction: Having a location, and a distant point, to create arc.
I need a counter-equation that gives me the required DIST for a given angle.

i.e.
assuming str is 800, what is the value of dist so a would be 114 (or 68 or anything).

114 = Math.pow(900/dist, 1.5)) // ????

How can i solve this equation for dist ?

thanks,


texts: Button onClick in a menu prefab doesn't work

texts:
I don't seem to be able to make a reference to a Button inside a menu prefab.
My menu prefab consists of a panel and the panel has 4 buttons.
I added
public GameObject prefabMenu;

in my code and drag and dropped the prefab in the Unity Editor to it.
When my scene is starting (Start() method) I instantiate this prefab into a GameObject like this:
panelMenu = Instantiate(prefabMenu, canvas.transform);

after that I try to refer one of the buttons with this line and set an onClick listener:
btnResume = panelMenu.transform.Find("BtnResume").GetComponent<Button>();
btnResume.onClick.AddListener(() => Log.I("Working"));

The log method however doesn't not get called when I click on the button (I checked and the btnResume is not null).
I appreciate any help on this. Thank you.


texts: What would be a good way to scroll a large html canvas (that contains little repetition if any)

texts:
What would be a good way to scroll the content of a huge html5 canvas so that the scroll is crisp and smooth, and memory consumption (and cpu load or battery consumption) is also reasonable?

any good library that can take care of it for you? Any specific plotting algorithm that will avoid a jumpy feel?

I guess the best way is to pre-plot upwards and downwards of the current viewport, but if the user quickly scrolls a whole lot up, I assume that some algorithms outperform others.

My canvas has very little repetition drawn on it, in case it matters, and the content doesn't change much. Just a very very long canvas element that also contains a lot of text, and needs to smoothly scroll in the browser viewport.


texts: Relation between "Run in background" setting and OnApplicationPause method

texts:
I'm working on a game for mobile platforms (Android at the moment, in the future it should be available for iOS and WinPhone) and I want to trigger a certain method when the game is un-paused. For this I'm trying to use OnApplicationPause(bool paused) method (when the "paused" variable is false), but the process is not working as expected. These are my questions:

In the player settings, does the "Run in background" setting influence the build (since this setting can be found only in Web player/Desktop build tabs, and I'm creating an Android build).
The problem that we started to experience is that when the game is paused, it crashes and the player has to restart the game. Is this connected to the "Run in background" setting?
What is the relation between "Run in background" and OnApplicationPause - will the OnApplicationPause be called if the "Run in background" is checked?
What is the difference between OnApplicationPause and OnApplicationFocus (meaning, which actions change the focus and which will pause the game)?

The code that I'm trying to execute at the moment is fairly simple:

void OnApplicationPause(bool paused)
{
  if(!paused) AddCoins( x => PlayerPrefs.SetInt("CoinCount", PlayerPrefs.GetInt("CoinCount")+x));
}

The idea of this code is to add a certain number of coins if the player watches an advert (the number of coins is calculated by the ad provider).

Thanks in advance


texts: Creating LOS zones on a 2D grid for chase AI

texts:
I have a 2D grid, around 20x20, stored as an array. Each grid cell can contain an opaque object or not. I also already have an algorithm to calculate LOS between any two squares via Bresenham.

I want to implement an AI that chases the player in a step-time game. The current rules I have are (re-evaluated with this priority each step):

If we can see the player go get them (a step at a time with Dijkstra/A* pathfinding).
If we can't see the player go to where we last saw them.
If we can't see the player and are where we last saw them, give up and head home.

But I want to add a further rule:

If we can't see the player and are where we last saw them, but there is only one way they could have gone to now be hidden without coming past us, go that way.

This turns out to be really hard to detect. What I have wondered about doing is to assign each grid square one or more zone numbers, such that every square that is in a given zone can see all other squares in that zone; then if there is only one neighbouring zone than the guard has not visited the guard will move into it. However, the zones overlap and a ridiculously large number of them are generated for even simple maps (due to, for example, different parts of a room gradually becoming visible as you walk down a corridor into it) which makes this awkward or difficult, and the generation algorithm seems to be at least O(n^2) or worse. Alternatively the zones could be calculated as a navigation mesh but this seems very difficult to compute from a grid map.

Is there any way to do this without manually putting hints on the map?


texts: Minecraft Forge 1.8 referencing mod problem

texts:
I'm trying to make a Minecraft Forge mod. I've done this before, but I've never worked with entities. So I was trying to add an entity to the EntityRegistry, but I can't seem to reference the mod file as an object using this. It tells me that it expect Object mod, not TestMobs. What am i doing wrong?

Here is my code:

package com.scriptcoded.testmobs;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.registry.EntityRegistry;

@Mod(modid = Tutorial.MODID, version = Tutorial.VERSION)
public class TestMobs
{
    public static final String MODID = "testmobs";
    public static final String VERSION = "1.0";

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        EntityRegistry.registerModEntity(EntityTutorial.class, "Test mob", 1, this, 80, 3, true);
    }
}

The problem is in the line EntityRegistry.registerModEntity(EntityTutorial.class, "Test mob", 1, this, 80, 3, true);.

Any ideas?
Thanks for any help!


texts:
I would like to make a 2D tile based game, but, to make it look a bit prettier, I would need to skew textures so that it would look more like a 2.5D game.
So I thought maybe I should skew textures to something like this:

So far I only found one topic about it - http://forums.create.msdn.com/forums/p/37143/215098.aspx#215098

But I don't really understand it. Maybe some of you do, can tell me how to skew my sprites?


texts: How can I save a high score using PlayerPrefs?

texts:
I'd like to save the player's high score using Unity's PlayerPrefs API. This is the code I have so far:

public int coins;
public int score;
public int highscore;
public int points;
public Text pointsText;
public Text HighScore;
public Text Score;
public Text coinsText;

void start(){
    highscore = PlayerPrefs.GetInt ("HighScore");
}
void Update () {
    if(points > highscore){
        highscore = points;
        HighScore.text = ("HighScore: " + points);
        PlayerPrefs.SetInt ("HighScore", highscore);
        PlayerPrefs.Save ();
    }
    score = points;
    pointsText.text = ("x  " + points);

    Score.text = ("Score  " + points);
    PlayerPrefs.SetInt ("Score", points);

    coinsText.text = ("Coins  " + points);

}

However, it does not work. Every time I restart the game, the high score is 0 again. How can I make this work?


texts:
I'm having a hard time wrapping around how something quite stateful such as complex AI would be handled in a pure ECS (such as components being only data and systems operating on that data)
Things like different enemies in a game that cast different spells, or bosses with various phases and abilities like in an MMO.Usually i'd handle such a thing with data and behaviour components and state machines, but this violates the data-driven ECS paradigm.
Is there an easy way to handle this sort of behaviour in an ECS or is a different approach required?


texts: Can't assign animation to animation variable declared in script Unity2D

texts:
So I'm trying to have my script pause an animation when the user clicks. Here's what I have so far:

I defined the animation up at the top

public Animation anim;

and then further down,

 void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            anim["myAnimation"].speed = 0.0f;
        }

 }

Code gives no error, however in Unity I have a GameController object to which this script is attached to. The gamecontroller object has a vacant field into which I drop my animation to. The issue is that when I try and drag and drop my animation or try to place it into that field, nothing happens, I keep getting the error down at the bottom saying that "The variable anim of GameController has not been assigned." How do I go about assigning myAnimation to the variable anim?

When I try and drag and drop my animation file to this, nothing happens. This is under the GameController script which I assigned to a GameController object.


texts: How are win conditions handled in a turn based game?

texts:
Turn based games sometimes have different win conditions for different maps and mission.

For example, control some structure for X turns, last X turns without losing a single soldier.

They usually also have standard win conditions across all maps like eliminate all enemy units and structures, etc.

How would I implement map/mission specific win condition checks?

My current implementation utilizes a finite state machine that loads the play state. The play state has objects and logic for gameplay. I could write custom play states for each mission, but I feel like that is not the best way to go as I would have large portions of duplicate logic and code.

Ideally I would like to tie in win conditions into my map/mission file data. When I load a map, the win conditions are loaded also, but am not sure how I would achieve that.

Any suggestions?


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

texts:
Ok so I have a big list of all my entities which I loop through and update. In AS3 I can store this as an Array (dynamic length, untyped), a Vector (typed) or a linked list (not native). At the moment I'm using Array but I plan to change to Vector or linked list if it is faster.

Anyway, my question, when an Entity is destroyed, how should I remove it from the list? I could null its position, splice it out or just set a flag on it to say "skip over me, I'm dead." I'm pooling my entities, so an Entity that is dead is quite likely to be alive again at some point. For each type of collection what is my best strategy, and which combination of collection type and removal method will work best?


texts: Angle between start and current rotation

texts:
I'm facing problem of the operations on rotations. I have a wheel with a start rotation of (0, 0, 0). The player has to rotate wheel 270 degrees in Y axis either left or right.
During the rotation slider should indicate progress of the rotation. For example if player rotated 135 degrees in right direction, slider is 50% filled to the right.
The thing is that I'm not sure how to get the value of which the player rotate the object.
For example when I start rotating right my angle changes from (0, 0, 0) to (0, 359, 0). How can I resolve this issue so it knows that change from (0, 0, 0) to (0, 359, 0) means player rotated only +1 degree?


texts: I am trying to collect some data from UNITY but it is taking forever. I increased the framerate to 5 which accelerated the simulation without compromising the output but still it's slow. I am wondering if I further increase the framerate, will it have any negative impact on the quality of simulation. Can anyone suggest what could be the best framerate to speed up the simulation without compromising on quality or is there any other way to speed up the simulation.


texts: Faking a 3D object to decrease number of polygons

texts:
I'm making a game in unity and I'm building a fence in blender but I want it to be as low poly as possible. My original design was too high poly so I thought, what if I could simply use a cube with some cleverly arranged textures. Like so:

You can see the edges are all looking good but the inside sections are not, i.e there's nothing there... so does anyone know if it's possible to fake those faces that would make it look as though it were a complete mesh. Here's what I'm tring to achieve:


texts:
I tried to create something to parse XML with, which needs the inclusion of the Microsoft.Xna.Framework.Content.Pipeline; reference. This was fine and all, but as soon as I tried to debug, I got the error that it could not be resolved because it was in the wrong target framework; my main project uses the Client one.

What confuses me is that I can use the SkinnedModelProcessor in the same solution with no problems when it uses said non-Client framework. Why is this? Can I get mine to work without changing the main project's target framework?


texts: If (button.interactable) condition doesn't work - why?

texts:
I have a Typewriter script attached to the text, which is a child of a button.
I want this script to run only if the button is interactable.

I made a public variable to store the button and used GetComponent() method, but it doesn't work.

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

// attach to UI Text component (with the full text already there)

public class UITextTypeWriter : MonoBehaviour {

public Text txt;
string story;
public Button ParrentButton;

void Awake()
{
    txt = GetComponent<Text>();
    story = txt.text;
    txt.text = "";

        Button b = ParrentButton.GetComponent<Button>();
        if (b.interactable)
        {
            StartCoroutine("PlayText");
        }
}

IEnumerator PlayText()
{
    foreach (char c in story)
    {
        txt.text += c;
        yield return new WaitForSeconds(0.125f);
    }
}

}

Where is my mistake? I would be grateful for your help!

Thank you in advance!


texts:
I'm working on an animation and model exporter from Maya to use within my game. Currently, models work perfectly, and animations have some issues with the joints. Since Maya works in an OpenGL environment and my game works with DirectX, to load the mesh in I negated the Z component of all vertex positions, normals, and inverted the UV's V coordinate.

Currently, joints loaded in are reversed along the Z axis. My question is, what do I need to do to get bone matrices working properly from OpenGL to DirectX? My original thought was to just transpose them, but that doesn't work. I've also tried negating the z-column but that causes some odd stretching.

I've only been trying to invert the root bone.

Notice the feet joints pointing backward.
http://i.stack.imgur.com/6kNr2.png

Inverting the root joints Z-Column, weird stretching and it looks like he's slouched.
http://i.stack.imgur.com/KysH8.png

Any thoughts on this?


texts: I know that my super simple multiplayer setup is probably not a good idea, but why?

texts:
I'm making a simple little MOBA just for fun. I was making everything single-player then I realized "oh crap I should probably add multiplayer, huh."

I've never done anything with networking before, so learning how to integrate Lidgren into my game was fun and awesome. The thing is, I pretty much know the way I'm doing things is wrong, because it's not robust enough for mainstream games to use, as far as I know, but what's wrong with it?

What I'm doing is, basically, whenever a player does an action, it sends a message to the server saying "hey, I just did this thing." The server and the client are both running the same simulation. The server then sends a message to all other clients telling them that that guy did that thing.

For the most part, except in a few cases, when a player does a thing, the client assumes it's cool and goes ahead with it on its own. So when you right-click somewhere to move there, that player's client just starts moving his guy there, and then sends a message to the server telling it about it.

So basically:

Player 1 casts a spell to make him move 100% faster for six seconds
Player 1's local client adds that buff to his Unit object
Player 1's client sends a message to the server saying "hey I just cast this spell"
The server makes sure he really did have enough mana to cast that spell, and if so, adds that buff to the server's copy of that Unit object
The server sends a message to all other clients saying "hey this guy just cast this spell"
Every other client receives the message and goes "ah okay cool," and adds that buff to their local Unit object for that player

I've been skimming through stuff to see how big games do multiplayer, and it's kind of confusing for someone who's just starting to dabble in this stuff, but it looks like the Source engine sends a packet containing all of the changes to everything in the world every tick? Again, totally new to this stuff, but can you really push that much data that frequently?

Sorry if this is a bit rambly, but basically, I was wondering why my simpler system isn't the right way to go, because if it was, other games would use it, right?


texts:
I'm making a roguelike in C# with the Roguesharp libraries, in which the map can be as large as 200x200 cells. When I have an entity requiring pathfinding, I am using Roguesharp's built in pathfinding system (which I believe uses a variation on A*, with Manhattan movement instead of orthogonal movement).

When I have an entity pathfinding every turn (to path to the player, which may constantly move) the framerate roughly halves, but the game is still playable. However, when I add in more entities the framerate drops greatly. 10 entities leaves the game running at less than 1 fps and completely unplayable.

Clearly I am doing something wrong, games like Dwarf Fortress manage to have hundreds of entities running around maps this size with little trouble. Does anyone have suggestions for how I can get better performance.

The way it currently works is: whenever the player takes his turn (attacks, moves, etc.) the game loops through every entity, does the pathfinding for that entity and moves them. Is there a more efficient way to do this when the player is moving every turn?


texts: Draw/"rasterize" irregular circle onto a 2D grid

texts:
I'm using the midpoint circle algorithm to choose cells on a 2D grid which outline a circle. However, I need to incorporate some random noise so that I get an irregular circle, and this method won't work anymore given how it works. Another stack exchange answer describes an equation (the "pink noise" example) I'd like to try but I'm not sure on the best approach to implement it.

I can replicate the equation via code, but I'll need to start choosing grid cells/coordinates differently and I'm not sure the best solution.

How can I "rasterize" an irregular circle like this?


texts:
I want to play an animation but it seems that in The new version of unity it is harder.  I have an AnimationClip but I don't know how to play it.  I have been looking at this for 2 hrs now and i cant get it to work.

using UnityEngine;
using System.Collections;

public class FPSCamera : MonoBehaviour {

public float lookSensitivity = 5;
private float xRotation;
private float yRotation;
private float currentRotationX;
private Animation walking;

void Start() {
    // DONT KNOW HOW TO FIND AND START WALKING ANIMATION
}
void Update() {
    yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
    xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
    xRotation = Mathf.Clamp(xRotation, -90, 90);
    transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
}
}


texts:
I'm currently trying to change my project to use GL_TRIANGLE_ADJACENCY instead of GL_TRIANGLES.

Following this question, I have managed to construct my index buffer fine, but when it comes to the drawing stage, I'm getting unexpected results.

Here is my geometry shader code.
Bare in mind that I store my indices like so:

(vertex1/adjacent1/vertex2/adjacent2/vertex3/adjacent3)

Geometry Shader

    #version 330

    precision highp float;

    layout (triangles_adjacency) in;
    layout (triangle_strip, max_vertices = 3) out;

    smooth in vec2 vVaryingTexCoords[];
    smooth in vec3 vVaryingNormals[];

    smooth out vec2 gsUV;
    smooth out vec3 gsNormals;

    void main(void)
    {
        int i;

        for(i = 0; i < gl_in.length(); i++)
        {
            switch(i)
            {
                case 0:
                case 2:
                case 4:
                    gl_Position = gl_in[i].gl_Position;
                    gsUV = vVaryingTexCoords[i];
                    gsNormals = vVaryingNormals[i];
                    EmitVertex();
                    break;

                default:
                    break;
            }
    }
    EndPrimitive();
}

Any ideas?

EDIT

Just like to point out that setting the adjacent index to be the same as the vertex index, i.e v1/v1/v2/v2/v3/v3 still produces the same results.


texts:
I'm currently tasked with designing a small HTML5 game.
Having done everything by myself so far (3D models, codebase, game design, etc) I'm now at a point where I'm running out of time.

I've less than a day to animate and bind everything together. However, that's exactly my problem.

I was under the naive impression that everything would be easier if I went with pre-rendered 3D models. However, I didn't consider the most difficult part. Animation.

After having spent over an hour trying to figure out messiahStudio, I figured it's time to ask for outside help.

Is there any easier solution to 3D animation than 3D rigging? What I'm basically looking for is some sort of tool that allows me to simply grab and move/deform select polygons.

It doesn't have to be as life-like and accurate as rigging, just efficient enough.

Were the circumstances any different, I might just learn how to rig. But that's sorely out of scope right now.

PS:The models were created in Sculptris but are fairly low-poly.


texts: Measure a distance point to point in unity3D?

texts:
I tried to measure a distance point to point on my phone screen by using following code
Vector3 startPoint;
Vector3 endPoint;
public Camera cam;
float distanceX;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    if (Input.GetMouseButtonUp(0))
    {
        Vector3 endPoint = cam.ScreenToWorldPoint(Input.mousePosition);

        distanceX = Mathf.Abs(startPoint.x - endPoint.x);
        Debug.Log(distanceX);
    }
}

but this code does not give me the correct result and I don't know why..


texts: Making sprites move in oppsite direction of vector

texts:
I have a sprite that moves from the bottom left of the screen to the top right. What I want to know is how would i make it turn around and go in the opposite direction, and continue this loop.

I tried negating  the direction of the vector but that doesnt work.

This what i have right now:

public void create() {
    // Game Initialization
    v = new Vector2(Gdx.graphics.getWidth() - 0, Gdx.graphics.getHeight() - 0);
    v.nor();
    v.scl(100);

    spriteBatch = new SpriteBatch();
    bug = new Sprite(new Texture("EnemyBug.png"));
    bug.setSize(50, 85);
    bug.setOrigin(0,0);//Gdx.graphics.getHeight() / 5, Gdx.graphics.getHeight() / 5);
    bug.setPosition(1,1);//Gdx.graphics.getWidth() - 50, Gdx.graphics.getHeight() - 50);
    bug.rotate(v.angle());

    rotDeg = 5;
}

@Override
public void render() {
    // Game Loop

    Gdx.gl.glClearColor(0.7f, 0.7f, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    spriteBatch.begin();

    if(bug.getX() >= (int)(Gdx.graphics.getWidth() - 100) && bug.getY() >= (int)(Gdx.graphics.getHeight() - 100)){
        turn = !turn;
    }
    else if(bug.getX() <= 50 && bug.getY() <= 50){
        turn = !turn;
    }

    if(!turn){
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    bug.draw(spriteBatch);
    spriteBatch.end();
}


texts: For a real-time PvP game, what network service would get the job done?

texts:
The game is between two players, real time, and has to be very synchronized - latency will certainly favor one player over the other.
It's built for iOS and Android and every touch on one end has to be instantanious on the other end.

The game will be built on Corona SDK and I'm looking to use a service to simplify communication (even if it involves additional costs). I'm currently considering PubNub or Parse.

I'm new to game dev and this is my first real time game. Please be as specific as possible.


texts:
Is there a way to start and stop a shader?.

I want to use this shader to sweep once over my texture and then stop. Does anybody know how to do that?

void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
    vec2 r = fragCoord.xy / iResolution.xy;
    r.y = 1.0 - r.y;

    vec4 tex = texture2D(iChannel0,r.xy);
    tex += vec4((sin((r.y)+r.x + iGlobalTime*3.)) + tex)/2.;

    fragColor = tex;
}


texts: Resolving contradictions in WFC more efficiently than naive backtracking

texts:
I just recently got started with the Wave-function-collapse Algorithm (WFC) in 3-dimensional space. I got the fundamentals working and wanted to now move on to let the algorithm automatically resolve possible upcoming contradictions/error-states.
For this, I (inspired by this Tweet from Oskar Stålberg) created a highly constricted Tileset that will run into such contradictions quite often.

(Some examples of constructed Levels in a (3x3x3)-Grid using this tileset.)
Note that this tileset will, for example, always run into a contradiction if the number of bottom contacts is odd since every pipe that comes out must also finish at the bottom.I've now implemented basic (naive) backtracking, which means whenever the algorithm runs into a contradiction, it goes back to the last decision made undoes it and tries another. This does work, however, because the possibility space for placed modules can become huge, it may resolve in a really slow generation trying out every possibility before having backtracked far enough to resolve the modules that caused this contradiction. (Gif 1, Gif 2)

Now I'm looking to optimize this algorithm.
I thought about using Backjumping instead of Backtracking with a quadratically increasing jumping distance each time it runs into the same contradiction again (first time we jump back 1, then 2, then 4, 8, 16, ...). But I'm not sure how to detect the overcoming of the first contradiction to be able to then reset the jumping distance.
I also don't get Oskar Stålberg's solution to this. In the post's comments, he speaks of cutting out Chunks to try and resolve the contradiction but how does he calculate these chunks?


texts: How to make it two seconds for Time.time?

texts:
var targetscript : Diamond;
var red : Color;
var orange : Color;

function Start () {
    gameObject.camera.backgroundColor = red;
}

function Update () {
    if (targetscript.score > 4) {
        gameObject.camera.backgroundColor = Color.Lerp(red, orange, Time.time);
    }
}

So right now, if the score is larger than 4 then it would change the camera background color to orange with lerp. But its too quick. I read on the internet that Time.time is 1 second. What is the alternative way but for 2 or 3 seconds? I tried this : http://answers.unity3d.com/questions/328891/controlling-duration-of-colorlerp-in-seconds.html
I tried the code for the voted answer but it didn't work. It still lerps through quickly. Does anyone have any ideas? Thanks


texts:
A project I am working on right now features a lot of "traffic" in the sense of cars moving along roads, aircraft moving aroun an apron etc.

As of now the available paths are precalculated, so nodes are generated automatically for crossings which themselves are interconnected by edges. When a character/agent spawns into the world it starts at some node and finds a path to a target node by means of a simply A* algorithm. The agent follows the path and ultimately reaches its destination. No problem so far.

Now I need to enable the agents to avoid collisions and to handle complex traffic situations. Since I'm new to the field of AI I looked up several papers/articles on steering behavior but found them to be too low-level. My problem consists less of the actual collision avoidance (which is rather simple in this case because the agents follow strictly defined paths) but of situations like one agent leaving a dead-end while another one wants to enter exactly the same one. Or two agents meeting at a bottleneck which only allows one agent to pass at a time but both need to pass it (according to the optimal route found before) and they need to find a way to let the other one pass first. So basically the main aspect of the problem would be predicting traffic movement to avoid dead-locks.

Difficult to describe, but I guess you get what I mean. Do you have any recommendations for me on where to start looking? Any papers, sample projects or similar things that could get me started?

I appreciate your help!


texts: Directly pass from transform feedback buffer to fragment shader

texts:
I am building terrain using a lod algorithm and deferred cascaded shadowmaps. The tessellated terrain is about 6,000,000 triangles. I tried this using 2 methods.

1st method: Both the deferred shadow program and the drawing program use tessellation shaders to tessellate the terrain. The tessellation stage for each program is exactly the same.

2nd method: I have 3 programs. The first program tessellates the terrain and stores it on the GPU using transform feedback. The second program uses the transform feedback buffer to render to shadow depth buffer. The third program uses the transform feedback buffer to draws the scene. This way I avoid tessellating the terrain twice.

To my surprise, the 2nd method was actually much slower until I started using the separation of the tessellation phase to tessellate the terrain less frequently. Now the methods are about the same fps, but in the 2nd method the terrain mesh is being updated less frequently.

Shouldnt the 2nd method be faster even if I tessellate every frame like the first method? The only thing I can think of is that the passthrough vertex shaders for the shadow and main program both have to copy 6,000,000*3 vertices even though they are just passthrough shaders. In the first method, the data would be passed right from tessellation shader to the fragment shader. So...

Does a passthrough vertex shader use the transform feedback buffer data directly, or does it copy every single vertice (even though it's the same), and use the copied data?

...
{
    out_position = in_position;
    out_normal = in_normal;
    out_uv = in_uv;
}

Is there any way I can speed this up?

Thanks in advance :)

Edit:

I should note that the example is for the shadow  program, the geometry shader applies different mvp matrices, culls, and asigns layers.

In the main program, I use
    gl_Position=mvp*in_position;
to allow gl to cull back facing triangles, but the normals and uvs are still passthrough.


texts: Should I delete the textures I use in OpenGL ES 2 (Android)?

texts:
Say I have a skybox and the user can choose out of 2 sets of 6 textures (one for each face of the cube) to use on that skybox. For example if user selects set A, I load the textures (GLES20.glGenTextures etc) and put them on the cube.

However, if the user then selects set B, should I delete the textures I previously created? Or what's the standard way of dealing with textures that are (at least temporarily) no longer needed? Also, is texture deletion an expensive operation?

My app will include other scenarios similar to the above, so I might end up having 10-15 (or more) textures in memory with only a few of them displayed, therefore I expect deleting them is the way to go.


texts:
Consider the following: you have a space invaders game. The 'hero' has 2 abilities - a normal attack which shoots standard bolts of whatever and a special attack which hits harder. The special attack can't be spammed.

There are a lot of ways to approach it: Number of times it can be used per level. It will use energy which is slowly regenerated and many more, but for our example let's consider that the 'hero' will not have any of those options and that the only possibilities are:

1) The ability must be charged

2) The ability has a cool down.

The question is: "What is the difference to the player when having 1 button per ability and multiple abilities per button?"

Of course, by this point I have to share that our imaginary game is not made for touch screens (Since if it was then it is pretty obvious that you want as little buttons as possible)

What I can think of is that when holding the button to "charge" it will give the player the impression that something strong is going to be unleashed. The downside of  this is that this locks down the possibility to shoot the power up in the middle of combat.


texts: How do I make cars on a one-dimensional track avoid collisions?

texts:
Using three.js, I use a simple spline to represent a road. Cars can only move forward on the spline. A car should be able to slow-down behind a slow moving car. I know how to calculate the distance between 2 cars, but how to calculate the proper speed in each game update?

At the moment I simply do something like this:

this.speed += (this.maxSpeed - this.speed) * 0.02; // linear interpolation to maxSpeed

// the position on the spline (0.0 - 1.0)
this.position += this.speed / this.road.spline.getLength();

This works. But how to implement the slow-down part?

// transform from floats (0.0 - 1.0) into actual units
var carInFrontPosition = carInFront.position * this.road.spline.getLength();
var myPosition = this.position * this.road.spline.getLength();

var distance = carInFrontPosition - myPosition;

// WHAT TO DO HERE WITH THE DISTANCE?
// HOW TO CALCULATE MY NEW SPEED?

Obviously I have to somehow take current speed of the cars into account for calculation.

Besides different maxSpeeds, I want each car to also have a different mass (causing it to accelerate slower/faster). But this mass has to be then also taken into account for braking (slowing down) so they don't crash into each other.


texts: 9-Slicing Sprite for UI Image still stretches corners

texts:
I am currently trying to slice a sprite for an Image component. It's a rectangle with rounded corners on the left side. Those rounded corners are supposed to stay the same even when the image is stretched while the rest of the rectangle is supposed to stretch dynamically horizontally and vertically. I will never stretch the image vertically, which is why that point can be ignored.

I setup 9-Slicing for the sprite like the documentation suggests, but the corners on the left side are still getting stretched. What am I doing wrong?


texts: Create extra bullets, offset according to angle of spaceship?

texts:
I am trying to create a weapons upgrade for my Spaceship, using libGosu and Chingu (in Ruby). This question is about how to deal with this issue specifically in Ruby, and more specifically in libGosu.

In the player class I have tried several variations of the following:

def fire
  Bullet.create(:x => @x, :y => @y, :angle => @angle)
  Bullet.create(:x => @x + Gosu::offset_x(90, 25), :y => @y + Gosu::offset_y(@angle, 0), :angle => @angle)
end

It sort of works, but not exactly how it ideally should. For reference, this is what the Bullet class looks like:

class Bullet < Chingu::GameObject
  def initialize(options)
    super(options.merge(:image => Gosu::Image["assets/laser.png"]))
    @speed = 7
    self.velocity_x = Gosu::offset_x(@angle, @speed)
    self.velocity_y = Gosu::offset_y(@angle, @speed)
  end

  def update
    @y += self.velocity_y
    @x += self.velocity_x
  end
end

How should I construct "def fire" in order to get the extra bullets to align properly when the spaceship rotates?

In the first image (above) the bullets are separated as intended.

In the second image the bullets are clumping together when the spaceship is rotated.


texts:
I am developing a game/simulation where agents are fighting for land. I have the situation shown in the picture below:

These creatures are walking around and occupying pieces of land they step on if they are free. To make this more interesting, I want to introduce "patrolling" behaviour, such that agents are actually walking around their land to patrol from any intruders who may want to take it.

On the technical side, each square is represented as a x,y position as well as a dimension representing its side length. It also contains information on who occupies the square. All squares are stored in an ArrayList.

How can I introduce  patrolling behaviour? What I want is for each agent to patrol a certain portion of the area (they divide amongst themselves which areas they will patrol). The main issue I've found are as follows:

The area of land is very random, as seen in the picture. It is rather difficult to understand where the bounds are in each direction.
How they should agents split the regions to patrol?
Areas of land may be disjoint, since the opposing team may take territory from the middle.

I had an idea of taking the furthermost square in each direction, treating those as the boundaries of the area, and divide regions based on those boundaries, but this might include lots of irrelevant land.

How should I approach this problem?


texts:
Players take turns in taking a rectangular bite out of the bottom right corner of the bar, by shading a square, tighter with all the squares below and/ or to the right it. The top left-hand square is poisoned, and the player forced to eat the square loses.

How do I determine who is currently winning while the game is being played?
(Creating the game in Unity using c#)


texts: Delay for seconds when key is held down?

texts:
Hello I am very new to Unity and am trying to make a shooting game in which when the space key is pressed down the gun charges then shoots. I want it to wait for 0.3 seconds before the gun fires off because I want an effect to happen with a particle system(I confused animation with effect in the first post). Also the problem the script has is that the bullet would not fire at all when the space is pressed. Here is the scripts I wrote:

 void Start()
 {
     StartCoroutine("Shoot",0.3f);
 }

 IEnumerator Shoot()
 {
     yield return new WaitForSeconds (0.3f);
     Bam ();
 }

 void Bam()
 {
     transform.Translate (0, 0, 12);
 }

 void Update ()
 {
     if (Input.GetKey (KeyCode.Space))
         Shoot();
 }


texts:
public class AbilityOne : MonoBehaviour
{
    public PlayerHealth playerHealth;
    public float healthGain = 2f;

    void OnTriggerStay2D(Collider2D other)
    {
        playerHealth.currentHealth += healthGain * Time.deltaTime;
    }
}

Im getting this error and do not know how to fix it. Anyone know the problem?Assets\Scripts\Medic\AbilityOne.cs(12,9): error CS0266: Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)


texts: Modular enemy behaviour in a shmup - Delegates unsuitable?

texts:
I'm creating a shmup type game and trying to implement the enemy wave system, which includes the associated enemy behaviours like their movement and bullet patterns. I've tried to separate the concerns of each aspect through classes and then eventually linking them together like so (part psuedo code to remove irrelevant pieces) :

Class WaveInstantiate {
    private EnemyMovement enemymovement;

    public void MakeEnemy(Vector3 pos, Quaternion rot, Enemy.EnemyMove behaviour) {
        GameObject enemy = Instantiate (ship, pos, rot) as GameObject;
        enemy.GetComponent<Enemy> ().moveEnemy = behaviour;
    }

    public IEnumerator Wave1() {
        // Set spawn spots and no. of enemies
        // Make the calls to: MakeEnemy(pos, rot, enemymovement.SomeFunctionToMoveEnemy)
    }

    public IEnumerator Wave2() // etc
}

WaveInstantiate defines the objects that are in the waves. Waves are determined by a GameController keeping track of the waves. There is a MakeEnemy function that will Instantiate the enemy and apply the movement behaviour that is given from the wave

Class Enemy {
    public delegate IEnumerator EnemyMove(Enemy enemy);
    public EnemyMove moveEnemy;

    void Start() {
        // Do some setup

        StartCoroutine(moveEnemy (this));
    }
}

The Enemy class is the main class that encapsulates all of the things necessary for the Enemy to function. Will start a coroutine that runs the function that was given to moveEnemy delegate by the waveinstantiate class.

Class EnemyMovement {
    private BulletPatterns bulletpatterns;

    public IEnumerator ForwardThenBack(Enemy enemy) {
        // Move object forward
        yield return StartCoroutine(bulletpatterns.BulletsAtPlayer (enemy.rigidbody.position));
        // Move object back
    }

    // Define some other movements here also
}

A class that defines all of the movement behaviour and controls when the ship will shoot. Makes a call to a BulletPatterns function to determine what kind of bullet pattern this. These functions are used as the delegate implementations for moveEnemy

Class BulletPatterns {
    private GameObject playerShip;

    public IEnumerator BulletsAtPlayer(Vector3 spawnPos) {
        // Create some bullets that are being aimed at the player
    }
}

Defines various types of bullet patterns that may be called independently.

Now my implementation of this structure works, but the problem is when i want to tweak certain movement behaviours. It's natural to parametrise certain things you want to tweak and let the caller handle the values, but since the movement is defined by a delegate, it becomes difficult when certain movement behaviour functions need different parameters to tweak that behaviour. But delegates also provide a nice separation and abstraction away from the movement of any particular enemy; if you want to make some new movement behaviour you can just create a function that handles it and pass in that function to the delegate that handles moving.

Is using delegates like this salvageable in any way or does it require another way of thinking about this?


texts: Tic Tac Toe, Reinforced Learning and Hash Tables - Don't understand how to create a game

texts:
For my data structures course, we were asked to create Tic Tac Toe(3x3)that:

1) Has two player - dumb and smart(computer plays both sides)
2) Dumb player - "X" , always makes first move, and all of his moves are random.
3) Smart player - "O" relies on reinforced learning. Basically, he looks through the hash table(transposition table) created from the different game states learned from prev games and finds good move. Project specifications page has no information on the implementation of the "intelligence"

I don't understand how to handle 3). At what stage of the game, board's hash needs to be inserted into table ? How Smart player decides on his next move ?

Thanks !


texts: In Photon, What happens networked GameObject's ownership when master client disconnects?

texts:
I'm creating multiplayer game with Photon. When player disconnects, especially master client does, every GameObject instantiated from Master client is gone, so I can prevent with this:

PhotonNetwork.autoCleanUpPlayerObjects = false;

Now GameObjects are still there even Master is gone, but what about their ownership? I needed to destroy some of enemies when they dies, but if master is gone and other player got selected as Master, is he automatically receive ownership of them too?

If not, is there a way to do that automatically? Any advice will very appreciate it!


texts:
How would I go about determining the difference in cost between changing the render color of an object every frame vice changing the texture (same sheet, just changing the source rectangle) every frame?

I ask because right now i'm changing the alpha every frame on about 300-400 objects, and i'm wondering if it isn't cheaper to just simulate that with a couple of frames and cycling through them.


texts: Alternative to world/terrain editing with jmonkey

texts:
I have been studying Java for almost a year and have been trying to develop a game using jMonkey. I have tried Unity before but since I only know Java I decided to go with jMonkey.

My problem is that the terrain/world edit in jMonkey is buggy. When I make changes to the terrain I sometimes can not save. Many others seem to have the same problem too.

I would also prefer drag n drog exactly like Unity has, but jMonkey doesn't seem to have that.

Is there any other way I can create the terrain/world (with drag n drop like Unity) and then import into jMonkey? What are the alternatives?


texts: Learning Curve of GameMaker and its limits

texts:
I am a Data Scientist and the last couple of years, I work also as a Game Designer (not Game Development). I have not thought to create a game by myself, up to now.

As a DS, I know programming, but I am not interested to learn a new language only for a game development. Like Unity or C/C++.

Also, I am not keen on creating a 3D game which may take 1-2 years to finish it working part time on it. So, I am closer to a 2D game, with the simplest one like Flappy Bird and the most difficult one like Angry Birds for mobile devices.

After a short research, I found GameMaker which seems reasonable in the difficulty. However, I would like to know what is its learning curve based on a pure programming language for gaming like Unity, plus if it has any limits of what you could do on a 2D game.


texts: Why is my obj file imported into pyglet showing a blank screen?

texts:
I am trying to figure out how to import .obj files generated using Blender into my Pyglet game. There is an importer object, example code, and an example .obj/.mtl file within Pyglet's contrib directory.

The pyglet contrib version works (and is flickery; comment out w.flip) with the pyglet/contrib .obj/.mtl files. When I try to run it with my .obj and .mtl files I get a blank screen.

Why am I seeing a blank screen instead of my Blender-generated object?

FWIW, here's my test repo.


texts: Unity, weird error appearing after playing in editor

texts:
got a bit of a weird error, hopefully someone here can help.

So I have created a custom class (does not derive from Monobehavior).

Then I have a variable for the class, in the Start() method I set it to 'null', first time I play it in editor, everything is fine, (pickups/weapon switching etc..), but then when I play it again after a while, the variable is not null, even though I set it to null in Start().

Here's the code to make it easier:

[System.Serializable]
public class Weapon
{
    public string weaponName;
}

public class PlayerFPS : MonoBehaviour
{
   public Weapon secondary;

   void Start(){
      secondary = null;
      print(secondary == null); //this returns True the first time I play, but False after
   }
}

It seems that for some reason after playing in the editor, the variable stops setting to 'null'.

I do a lot of Instantiating and Destroying, so perhaps, the issue is somehow related to Garbage Collector or Cache?

Thanks in advance!


texts: Game prelauncher with configurations (resolution/quality)

texts:
I've seen that a lot of games have the exactly same configuration screen before the game launches, as you can see in the following screenshot.

Is this screen generated by some tool, for example, Unity, GameMaker or anything, or is it a plugin that we can use?


texts: How do i instantiate a particle system on gameObject destroy?

texts:
I have this damage script and I want it to instantiate a particle system...a death effect on enemy destroy. How do i add that to this script, please?

using UnityEngine;
using System.Collections;
using UltraReal.Utilities;
using UltraReal.WeaponSystem;

public class BasicDamage : UltraRealDamageBase
{

    /// <summary>
    /// Reference to a damage sound effect
    /// </summary>
    [SerializeField]
    protected AudioClip _damagedSound = null;

    /// <summary>
    /// Reference to a death sound effect
    /// </summary>
    [SerializeField]
    protected AudioClip _deathSound = null;

    /// <summary>
    /// Reference to Audio Source. If none is provide, it will try to get the one on the game object.
    /// </summary>
    [SerializeField]
    protected AudioSource _audioSource = null;

    /// <summary>
    /// Overriden OnStart method from UltraRealDamageBase.
    /// </summary>
    protected override void OnStart()
    {
        base.OnStart();

        _audioSource = GetComponent<AudioSource>();
    }

    /// <summary>
    /// Overriden OnDeath method from UltraRealDamageBase.
    /// </summary>
    protected override void OnDeath()
    {
        base.OnDeath();

        if (_audioSource != null && _damagedSound != null)
            _audioSource.PlayOneShot(_deathSound);

        Destroy(gameObject);
    }

    /// <summary>
    /// Overriden OnDamaged method from UltraRealDamageBase.
    /// </summary>
    protected override void OnDamaged(float damage)
    {
        base.OnDamaged(damage);

        if (_audioSource != null && _damagedSound != null)
            _audioSource.PlayOneShot(_damagedSound);
    }
}


texts: How would I go about merging two models together in-game to create a new model?

texts: Let's say I have two models: model 1 is hilt and model 2 is blade. How would I merge these to models together to create a sword?


texts: Unity: Running code on the "Create Other" menu?

texts:
Right now I am trying to create a TextMesh GameObject from code.

The graphics primitives are accessible through PrimitiveTypes, I'm thinking there must be something similar, and if not, I could at least run whatever static function is bound to the menu - if only I knew the name.

The more general question is "how one get at all the other items on the "Create Other" without using the menu itself?"


texts: How do I make a collision between AABBs slide?

texts:
I have a room with objects inside. Each object has it's own AABB.

I know how to check for collisions between the objects with an AABB-AABB intersection.

How do I calculate an appropriate collision response to make them frictionlessly slide against each other as they collide?


texts: Unity : callbacks in component based design

texts:
I am trying to use component based design in Unity3d v5. If I have 2 separate C# scripts attached to enemy ships like below:

Script1.shipDead() - Remove game object and show explosion animation
Script2.showPoints() - Destroyed ship shows points ex: +100 (later this will fade away)

How can I perform showPoints() function after shipDead() function has been performed, as a callback?

I can't put both actions in the same function, as some enemies will not have points.
Some enemies will leave power ups/ small enemies/ bombs after being destroyed.

And I don't want to duplicated the same code in 4 functions.

Like :

function 1: destroy ship (nothing more)
function 2: destroy ship + show points
function 3: destroy ship + spawn small enemies
function 4: destroy ship + show points + spawn bomb

(As you can see above, there are many different possibilities / combinations I can come up with)

I need to separate functions and isolate them to do individual tasks. As shipDead() will not do anything related to showPoints() or showPowerUp() functions.

My question is how can I perform functions sequentially? One after another, like a callback function?

Like this:

run Script1.DestroyShip() first;
after that run Script2.ShowPoints();
and finally run Script3.SpawnBomb();

Please provide a solution that will not violate the following:

Components needs to be reusable (I can drag and drop the scrip in to other enemies/ships)
Code shouldn't be duplicated
Loosely coupled (Lesser dependancies)

Please help me on this, Thanks in advance!


texts: Floor is made up of tiles with their own box colliders. Pushable item gets stuck on the "seams"

texts:
So I have a scene where the floor is made up of some tiled objects. All of these have the exact same height and exact same Y position. I also have a block with a rigidbody that you can push on the ground. It has a rigidbody with freeze rotation enabled for X, Y, and Z.

My issue is this: when pushing the block around, it sometimes gets stuck when reaching the seams of the tiled objects. I have tried giving it a friction of 0, but it still gets stuck sometimes. Is there any solution for this, other than manually creating a big collider that spans the entire floor?


texts: Drawing texture does not work anymore with a small amount of triangles

texts:
When I draw lines, the vertices are well connected. But when I draw the texture inside the triangles, it only works with i<4 in the for loop, otherwise with i<5 for example, there is a EXC_BAD_ACCESS message, at @synthesize textureImage = _textureImage. I don't understand why. (The generatePolygons method seems to work fine as I tried to draw lines with many vertices as in the second image below. And textureImage remains the same for i<4 or i<5 : it's a 512px square image).

Here are the images :

What I want to achieve is to put the red points and connect them to the y-axis (the green points) and color the area (the green triangles) :

If I only draw lines, it works fine :

Then with a texture color, it works for i<4 in the loop (the red points in my first image, plus the fifth one to connect the last y) :

But then, if I set i<5, the debug tool says EXC_BAD_ACCESS at the synthesize of _textureImage. Here is my code :

I set a texture color in HelloWordLayer.mm with :

CCSprite *textureImage = [self spriteWithColor:color3 textureSize:512];
_terrain.textureImage = textureImage;

Then in the class Terrain, i create the vertices and put the texture in the draw method :

@implementation Terrain

@synthesize textureImage = _textureImage; //EXC_BAD_ACCESS for i<5

- (void)generatePath2{
    CGSize winSize = [CCDirector sharedDirector].winSize;
    float x = 40;
    float y = 0;
    for(int i = 0; i < kMaxKeyPoints+1; ++i) {
        _hillKeyPoints[i] = CGPointMake(x, y);

        x = 150 + (random() % (int) 30);
        y += 30;
    }
}

-(void)generatePolygons{

    _nPolyVertices = 0;
    float x1 = 0;
    float y1 = 0;
    int keyPoints = 0;

    for (int i=0; i<4; i++){ /* HERE : 4 = OK / 5 = crash */
        //V0: at (0,0)
        _polyVertices[_nPolyVertices] = CGPointMake(x1, y1);
        _polyTexCoords[_nPolyVertices++] = CGPointMake(x1, y1);

        //V1: to the first "point"
        _polyVertices[_nPolyVertices] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);
        _polyTexCoords[_nPolyVertices++] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);

        keyPoints++; //from point at index 0 to 1
        //V2, same y as point n°2:
        _polyVertices[_nPolyVertices] = CGPointMake(0, _hillKeyPoints[keyPoints].y);
        _polyTexCoords[_nPolyVertices++] = CGPointMake(0, _hillKeyPoints[keyPoints].y);

        //V1 again
        _polyVertices[_nPolyVertices] = _polyVertices[_nPolyVertices-2];
        _polyTexCoords[_nPolyVertices++] = _polyVertices[_nPolyVertices-2];

        //V2 again
        _polyVertices[_nPolyVertices] = _polyVertices[_nPolyVertices-2];
        _polyTexCoords[_nPolyVertices++] = _polyVertices[_nPolyVertices-2];

        //V3 = same x,y as point at index 1

        _polyVertices[_nPolyVertices] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);
        _polyTexCoords[_nPolyVertices] = CGPointMake(_hillKeyPoints[keyPoints].x, _hillKeyPoints[keyPoints].y);

        y1 = _polyVertices[_nPolyVertices].y;
        _nPolyVertices++;
    }
}

- (id)init {
    if ((self = [super init])) {
        [self generatePath2];
        [self generatePolygons];
    }
    return self;
}

- (void) draw {

    //glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);

    glBindTexture(GL_TEXTURE_2D, _textureImage.texture.name);

    glColor4f(1, 1, 1, 1);
    glVertexPointer(2, GL_FLOAT, 0, _polyVertices);
    glTexCoordPointer(2, GL_FLOAT, 0, _polyTexCoords);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nPolyVertices);

    glColor4f(1, 1, 1, 1);
    for(int i = 1; i < 40; ++i) {
        ccDrawLine(_polyVertices[i-1], _polyVertices[i]);
    }

    // restore default GL states
    glEnable(GL_TEXTURE_2D);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

}

Do you see anything wrong in this code?


texts: Rendering differences between ps_1_3 and ps_2_a

texts:
I am trying to update a shader from ps_1_3 inline assembly to ps_2_a HLSL. However the HLSL shader causes things to render differently when using ps_2_a. When using my HLSL conversion with ps_1_3 it works same way as with the inline assembly.
Original assembly
Sampler[0] = (DiffuseMapSampler);
pixelShader = asm
{
    ps_1_3
    tex t0
#ifdef _POINTLIGHT_
    add r0.rgb, v0, v0
    +mov r0.a, v0.a
    mul_x4 r0, t0, r0
#else
    mul_x4 r0, t0, v0
#endif
#if defined(OVERGROWTH) && HASALPHA2MASK
    mul_x2 r0.a, r0.a, t0.a
#endif
};

Sampler and VS_OUTPUT
struct VS_OUTPUT
{
    float4 Pos  : POSITION0;
    float2 Tex0 : TEXCOORD0;
#if _HASSHADOW_
    float4 TexShadow    : TEXCOORD1;
#endif
    float4 Color  : COLOR0;
    float Fog   : FOG;
};

texture DiffuseMap;
sampler DiffuseMapSampler = sampler_state
{
    Texture = (DiffuseMap);
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    AddressU  = WRAP;
    AddressV  = WRAP;
    MipMapLodBias = 0;
};

My HLSL translation
float4 basicPixelShaderNoShadow(VS_OUTPUT VsOut) : COLOR
{
    float4 diffuseMap = tex2D(DiffuseMapSampler, VsOut.Tex0);
    float4 outCol;
#ifdef _POINTLIGHT_
    outCol.rgb = VsOut.Color.rgb + VsOut.Color.rgb;
    outCol.a = VsOut.Color.a;
    outCol = (diffuseMap * outCol) * 4;
#else
    outCol = (diffuseMap * VsOut.Color) * 4;
#endif

#if defined(OVERGROWTH) && HASALPHA2MASK
    outCol.a = (outCol.a * diffuseMap.a) * 2;
#endif
    return outCol;
}

And this is the result in game

For some reason when using ps_2_a the colours are oversaturated.
Edit:
HLSL that fixed the issue:
float4 vertexColor = float4(VsOut.Color.rgb, VsOut.Color.a*2);
float4 diffuseMap = tex2D(DiffuseMapSampler, VsOut.Tex0);

float4 outCol = diffuseMap * vertexColor * 2;

#if defined(OVERGROWTH) && HASALPHA2MASK
outCol.a *= 2 * diffuseMap.a;
#endif

return outCol;

dont quite understand why, but it works :)


texts: CCParticleSystemQuad works as intended every second time

texts:
I'm using CCParticleSystemQuad for particles, loading it from plist:

flourEmitter = [CCParticleSystemQuad particleWithFile:@"FlourParticles.plist"];

But it works not every time. Every second or third time I start a game, particles look different from what I've set them up and there are errors saying it couldn't load image.

cocos2d: CCTexture2D. Can't create Texture. cgImage is nil
cocos2d: Couldn't create texture for file: in CCTextureCache

Of course the image is there and the next time i launch game it works as intended.

I cannot think of any ways how to debug this error.


texts: How can I analyze which level on which of three difficulty settings causes players to quit my game?

texts:
I have a puzzle game with N stages where each stage has 3 difficulty levels. Users have to finish current unlocked stage to access next stage, but they can access any difficulty level for unlocked stage.

As example, User A played stage 1 with difficulty level EASY, then he changed the difficulty level to HARD and finished stage 2.

I'm using Flurry Analytics to log as above: "stage1_Completed_Easy" and "stage2_Completed_Hard"

The problem is: there could be more users completed stage N than those who sompleted stage N-1
As example,  there are:

100 players completed stage1 EASY
50 players completed stage1 HARD
50 players completed stage2 EASY
25 players completed stage2 HARD
70 players completed stage2 NORMAL

I'm making assumption that each player only completed each stage once. This means from stage 1 to stage 2, I'm losing 5 players

I want to know which level and what difficulty that makes users stop playing my game


texts: Should I slow down my animation with co-routines or update the animation state?

texts:
I want to

gradually stop the car animation as it collides with another car
gradually speed up the car animation as it exits the collider

I have two ways to achieve this.

Update
Co-routine

For co-routine I used this piece of code:

IEnumerator IncreaseSpeedGradually1(AnimationControlSpeed lastGOHitScript)
{
    //stop if decrease speed in progress
    StopCoroutine("DecreaseSpeedGradually");
    float decrementValue = ((lastHitVehicleSpeed / 2) * 2);
    while (lastGOHitScript.Speed <= lastHitVehicleSpeed)
    {
        lastGOHitScript.Speed += decrementValue * Time.deltaTime;
        yield return 0;
    }
    //setting speed to the last speed
    lastGOHitScript.Speed = lastGOHitScript.iniSpeeed;
}

and for the update-based approach I just added this criteria to the method:

if (carAnimState == carAnimationState.starting)
{
    carAnimState = carAnimationState.running;
}

if (carAnimState == carAnimationState.stoping)
{

    carAnimState = carAnimationState.running;
}

These are the two ways I thought about using. I wanted to ask which is right way to do this job? To slow down animation speed and hence get my objective? I guess co-routines can be problematic later in my game.
Are there performance concerns for using one of the approaches?


texts: Why does my ball always bounce perpendicular to walls?

texts:
I'm using Box2D.

I think it's something to do with wall's fixture definition, but when a ball goes toward a wall at a 45 degree angle, I would expect it to bounce off at 135 degrees, but it always goes 90 degrees against wall. Why would this be?


texts: Why is my FPS computation yielding higher numbers than I expect?

texts:
I have following code:

void Game::execute()
{
    isExit = false;
    init();

    double dt = 1.0 / 60.0;
    boost::timer timer;
    double accumulator = 0.0;

    boost::timer fps_timer;
    int fps = 0;
    while (isExit != true)
    {
        handleEvent();
        accumulator += timer.elapsed(); timer.restart();
        while (accumulator > dt)
        {
            accumulator -= dt;
            handleEvent();
            update(); // updating physics
        }
        if (fps_timer.elapsed() > 1.0) //if 1 second is elapsed
        {
            fps_timer.restart();
            m_fps = fps;  //m_fps - is result, which is rendered
            fps = 0;
        }
        else fps++;
        render(); // main rendering command
    }
}

And usually m_fps is equal 300-400. But I expect to see 30-60. Where I did wrong?


texts: Building a Plattformer - How to determine if a player is allowed to jump?

texts:
I'm building a simple Plattformer Jump n' Run Style game. I do not use tiles - instead i've geometrical shapes for my level entities (and the player is one too). I finished my collision detection code and everything works fine so far.

Next, I wanted to implement jumping. Just checking if the player hits the appropriate key and add some upwards velocity. Works fine. But it works even if the player is in-air, which is not what I want. ;-)

So, I have to check if the player stands on something. My first idea was to check if there was a collision in the last frame and mark the player as "able to jump", but this would even trigger if the player hits a wall in-air. As my math skills aren't that good, i ask for help - even hints would do how to implement this.

Thanks!


texts: Irrlicht app: Creating STL exception leads to segfault

texts:
I'm developing application with C++ language and Irrlicht engine.

When I add std::runtime_error("err") expression into my code, I got segmentation fault at address 0 (before entering to main). If instead I use std::exception(), app runs fine.

How std::runtime_error() causes segfault and how to fix it? Thanks!

#include <stdexcept>
#include <exception>
#include "irrlicht.h"

int main() {
    irr::IrrlichtDevice* device = irr::createDevice();
    if (!device)
        throw std::runtime_error("err");  //without this run fine
}

Compile:

g++ -ggdb -Wall -Wextra -std=c++11 -o main main2.cc \
-lIrrlicht -lGL -lXxf86vm -lXext -lX11 -lXcursor

Backtrace:

(gdb) bt full
#0  0x00000000 in ?? ()
No symbol table info available.
#1  0xb5d88fe1 in init () at dlerror.c:177
No locals.
#2  0xb5d8942e in _dlerror_run          (operate=operate@entry=0xb5d88e10 <dlsym_doit>,     args=args@entry=0xbffff160) at dlerror.c:129
    result = <optimized out>
#3  0xb5d88e98 in __dlsym (handle=0x0, name=0xb7f8afe5  "posix_memalign") at dlsym.c:70
    args = {handle = 0x0, name = 0xb7f8afe5 "posix_memalign", who = 0xb7f674bc, sym = 0xb5d65b20}
    result = <optimized out>
#4  0xb7f674bc in ?? () from /usr/lib/nvidia-   304/libGL.so.1
No symbol table info available.
Backtrace stopped: previous frame inner to this frame     (corrupt stack?)

LD debug

LD_DEBUG=all LD_DEBUG_OUTPUT=log.txt ./main
tail log.txt.*

   3848:    symbol=__pthread_key_create;  lookup in file=/lib/i386-linux-gnu/libgcc_s.so.1 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/lib/i386-linux-gnu/libc.so.6 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/nvidia-304/tls/libnvidia-tls.so.304.131 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/nvidia-304/libnvidia-glcore.so.304.131 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libXext.so.6 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/lib/i386-linux-gnu/libdl.so.2 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libxcb.so.1 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/lib/ld-linux.so.2 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libXau.so.6 [0]
  3848: symbol=__pthread_key_create;  lookup in file=/usr/lib/i386-linux-gnu/libXdmcp.so.6 [0]


texts:
I'm not sure if I correctly understand 3D transformations in OpenGL. Let's assume I'm using the typical matrix stack.

It seems like you move the world X units over, drop in a bag of verts (a mesh) and move the world back by popping the matrix off the stack, then you repeat the process to place another model?

Say I wanted to place a model at (10, 0, 0) and another at (0, 10, 0). I think I would...

PUSH move(10,0,0);
DRAW model A;
POP;
PUSH move(0,10,0);
DRAW model B;
POP;

Some questions come to mind, like for example what does loading an identity matrix do in the stack?

Am I right to assume that these operations in effect move the world around, then you draw the mesh at 0,0,0 in world space when you've moved the world to your liking?

Or is it the other way around, does GL "apply" the matrix stack to your mesh as you draw it?

Thanks, -Cody


texts: throw a 2D ball facing the target to simulate a 3D like effect

texts:
How would you update the state of a 2D object that is thrown forward(with an arc) facing a target to simulate a 3D(depth) like effect?

var ball; //2D ball from a sprite sheet
ball.x = 0;
ball.y = 0;
ball.scaleX = 1;
ball.scaleY = 1;

ball.throw(); //set ball to a throwing state
ball.update(); //update the ball's positon and depth by calculating its current coordinates and scale.
ball.render();


texts: When does a game idea cross the line between homage/parody to ripoff?

texts:
I'm not sure where this question belongs, but as it pertains to the development of a game idea, I figured I'd try to post it here.

Recently I've been inspired to create a game based on another game I've played. However, the idea that I have is very similar to the original game. I was wondering, when does a game idea cross from being a homage or parody into the realm of being a ripoff? Are there any hard or fast rules or does this cross into a gray area?


texts: Syncing game states in a multiplayer RTS game

texts:
I'm working in a group with 2 friends on our Gr. 12 final project for programming. We're making a multiplayer RTS game. I've been assigned to the networking section of the game, and none of us have any experience doing network programming.

We've established that we'll have the server process everything such as path finding, build queues etc. The client will receive packets from the server, which will contain information such as HP, x, y, etc of each unit/building (Well, the server will send a packet whenever a unit/building's state such as losing HP, movements etc is changed).

The problem is identifying which unit the packet contains information for. I've thought of generating a number as an ID for each unit/building, and storing the units in a map data structure, where the key is the ID. Is there a better way to do this? How do most RTS games do it?


texts: How to wisely update body trajectories in a 3D space simulation game?

texts:
Suppose I have a Spacecraft object in 3D space, controllable by the player. I want it to update its own trajectory, so I give it a function for that (actually it might be inside a controller component associated with it). No problem until this point.

For this function I want to use a scientifically tested, accurate N-body simulation algorithm (like this). It's my field so I already know how to do that.

The challenge is how to make the game activate the function efficiently. This is what I've thought of so far:

The algorithm can calculate a lot of time steps in a short time, so I could activate it in one loop, save the trajectory data, and go on for several game loops using that data. During this time the spacecraft's position is updated every loop, but the algorithm is sleeping.
When the predefined number of loops has passed, or when the user gives a movement command, the algorithm is activated again, producing the new portion of the trajectory to use next.
This might require double-buffering.

The question is: who should be responsible for activating the spacecraft's algorithm? Should I do that directly in the game loop, or perhaps create a "timer object" that keeps track of the number of loops and user input and calls the function when appropriate? Something else?

Note that the same thing would happen for all the other bodies orbiting in space. However the other bodies would simply have to follow predefined trajectories, no need for an algorithm. The timer object could take care of updating all the trajectories at the right times.

Also, if you think there is a totally different and better way to do this, please let me know.

Additional info: the game is in C++, and the graphics engine is Ogre3D.

EDIT: changed the part about the trajectories of the non-interactive bodies, because comments here made me realize that it was plain stupid.


texts:
Should I just use the built-in sin() function or my custom sine function?
I'm concerned about performance here. I don't care about accuracy much here because I use it to just get wave effects in my shader.
The shader is for mobile platforms (OpenGL ES)
Here's my code
float customSin(float x){
   x = fract( 0.75 + x*0.159155 )*2.0 - 1.0;
   return x*x * (6.0 - 4.0*x) - 1.0;
}

Here's my algorithm
x is the input, y is the output
r = 0.75 + x/(π*2)
a = | r- floor(r) - 0.5 |*2
y = ( 3(a^2) - 2(a^3) )*2 - 1
I checked the graph, and it's pretty close to the actual sine.
Which one should I go with?


texts: Farseer Physics: How to create shape from Vertices?

texts:
As you can understand from the title, I'm pretty new to game development. I'm doing this for fun. Anyway here's my question.

I have this Farseer Physics samples and i've been studying them for a few days. One thing i can't understand is, how the vertices creates the shape? I mean, in the game sample, where you create a shape for your car from vertices, there is a code like this:

Vertices vertices = new Vertices(8);
vertices.Add(new Vector2(-2.6f, 0.10f));
vertices.Add(new Vector2(-2.375f, -0.46f));
vertices.Add(new Vector2(-0.58f, -0.92f));
vertices.Add(new Vector2(0.46f, -0.72f));
vertices.Add(new Vector2(2.7f, -0.07f));
vertices.Add(new Vector2(2.5f, 0.205f));
vertices.Add(new Vector2(2.3f, 0.23f));
vertices.Add(new Vector2(-2.55f, 0.35f));

PolygonShape chassis = new PolygonShape(vertices, 2f);

I understand you create a vertices list and add 8 points(?) to it and then you make a polygonshape from those vertices, a random shape created from your points(?). The thing i can't understand is what are those numbers which inside the Vectors? I mean where in the shape are those? Corners? Edges? or a line between those two floats? Or the line between the corners?

Now lets say I want to make a shape like this

http://i.stack.imgur.com/Ac7Dv.png

What are those vertices for this picture?
You can give random numbers thats not a problem, only thing I want to understand is, what are those Vectors on this picture? Thank you very much for your help and time.


texts: Keep running CGRectIntersect Method - Objective C

texts:
I have two UIImageViews. mainSprite, and enemy1. And I have a method that makes enemy1 start moving towards mainSprite. So here's that method.

-(void)enemy1Aggro{
if (CGRectIntersectsRect(mainSprite.frame, enemy1Aggro.frame)) {
    if (mainSprite.center.x > enemy1.center.x) {
        enemy1.center = CGPointMake(enemy1.center.x+2, enemy1.center.y);
    }
    if (mainSprite.center.x < enemy1.center.x) {
        enemy1.center = CGPointMake(enemy1.center.x-2, enemy1.center.y);
    }
    if (mainSprite.center.y > enemy1.center.y) {
        enemy1.center = CGPointMake(enemy1.center.x, enemy1.center.y+2);
    }
    if (mainSprite.center.y < enemy1.center.y) {
        enemy1.center = CGPointMake(enemy1.center.x, enemy1.center.y-2);
    }
}

}
This works because I'm calling it on an IBAction that is a button that gets held down. But the problem is that when that button stops being pressed, this method stops running. So what I need is a way to have this method keep on running. Maybe a for loop? I'm not using anything like cocos2d, and I'm not using CoreGraphics. If you need to see any more of my code just ask.

Thanks :)


texts:
I am trying to create a "wander" action that will make my NPC walk to a random position.

The catch is that the NPC should only go positions inside of a collider.

I have a huge Sphere that has a collider on it now I only want my NPC to go to positions that are inside that Sphere collider.

My question is how do i find a random position inside of a colider?

Update

So after testing i am unable to use colliders because the sphere is too big here is an image of my gameobject:

As you can see from the image I have a huge sphere that my NPC's will have to stay inside when wandering

In order to use the Collider.ClosestPoint() the collider has to be a Box, sphere or a mesh collider with a convex.

Sadly this is not feasible for me because the sphere should not collide with other objects.

So my question is how do I find a point inside this gameobject?


texts:
Could someone explain how to use the lookup tables provided on http://transvoxel.org/ with the regular Marching Cubes algorithm?

I'm not even talking about the whole LOD System etc. I actually understand how that is supposed to work and why Transvoxel uses different tables, I just can't seem to figure out what modifications to make to the regular Marching Cubes algorithm to use them.


texts: Textures occasionally rendering twice on a particular face

texts:
I am learning how to render 3D objects using webgl (no third-party libraries).

I am currently facing a very confusing situation however, where my textures are rendering apparently twice over a particular triangle, but only on some of the triangles.

I have added a screenshot of the problem, and was rather hoping some gl-ninja in here would be able to point me in the direction of my mistake:

As you can see, most of the textures are rendering fine, the cobble stones and most of the triangles of the crates, I hope it is clear enough, in the top-right triangle of the bottom left crate the system is showing 2 textures (1 incorrect, quite strong, the other correct, quite weak).

I don't really expect you to wave a wand and fix this (though that would be nice!) I'm just hoping that you recognise the symptoms and can point me in the right direction, either terms to use in Google, or areas in my code that I should give some more thorough scrutiny.

UPDATE:
I'm so thankful for your help!

Somehow my object had set itself to render as a trianglestrip, instead of a triangle list. I realise there's no way you could have seen that, just leaving this here in case some fellow coder is stuck on the same strange issue!

Been looking into this for days now... live and learn!


texts:
I watched the Unity Space Shooter video tutorials and then I have added a second player. I can not seem to get the 'Game Over' when they both die. It will happen when one player dies but not both. Below is my code.

using System.Collections;

public class DestroyByContact : MonoBehaviour
{
  public GameObject explosion;
  public GameObject playerExplosion;
  public GameObject player2Explosion;
  public int scoreValue;

  private bool P1Dead;
  private bool P2Dead;
  private GameController gameController;

  void Start ()
  {
    P1Dead = false;
    P2Dead = false;
    GameObject gameControllerObject = GameObject.FindWithTag ("GameController");

    if (gameControllerObject != null)
      gameController = gameControllerObject.GetComponent < GameController> ();

    if (gameController == null)
      Debug.Log ("Cannot find 'GameController' script");
  }

  void OnTriggerEnter(Collider other)
  {
    if (other.CompareTag ("Boundary") || other.CompareTag ("Enemy"))
      return;

    if (explosion != null)
      Instantiate (explosion, transform.position, transform.rotation);

    if (other.CompareTag ("Player"))
    {
      Instantiate (playerExplosion, other.transform.position, other.transform.rotation);
      P1Dead = true;
    }

    if (other.CompareTag ("Player2"))
    {
      P2Dead = true;
      Instantiate (player2Explosion, other.transform.position, other.transform.rotation);
    }

    if (P1Dead == true & P2Dead == true)
      gameController.GameOver ();

    gameController.AddScore (scoreValue);
    Destroy(gameObject);
    Destroy(other.gameObject);
  }
}


texts: How do audio based games such as Audiosurf and Beat Hazard work?

texts:
Note: I am not asking how to make a clone of one of these. I am asking about how they work.

I'm sure everyone's seen the games where you use your own music files (or provided ones) and the games produce levels based on them, such as Audiosurf and Beat Hazard.

Here is a video of Audiosurf in action, to show what I mean.

If you provide a heavy metal song, you would get a completely different set of obstacles, enemies, and game experience from something like Vivaldi.

What does interest me is how these games work. I do not know much about audio (well, data-side), but how do they process the song to understand when it is settling down or when it's speeding up? I guess they could just feed the pitch values (assuming those sorts of things exist in audio files) to form a level, but it wouldn't fully explain it.

I'm either looking for an explanation, some links to articles about this sort of thing (I'm sure there's a term or terms for it), or even an open-source implementation of this kind of thing ;-)

EDIT: After some searching and a little help, I found out about FFT (Fast Fourier Transform). This maybe a step in the right direction, but it is something that does not make any sense to me..or fits with my physics knowledge of waves.


texts: cocos2dx - Custom Fragment Shader and CCRenderTexture

texts:
I have a CCRenderTexture that is filled with a sprite when the scene is loaded, as follows,

canvas = CCRenderTexture::create(this->getContentSize().width, this->getContentSize().height);
canvas->setPosition(data->position);
canvas->beginWithClear(0.0, 0.0, 0.0, 0);
this->visit();
canvas->end();

The above code is written within a class, which derives from CCSprite (Hence this).

Then, in another function applyShader(), I create a sprite named splat, from the texture of CCRenderTexture *canvas. Thus splat will contain the whole texture of canvas.

Now I apply a custom fragment shader to the splat by calling the function splat->renderShader(), which will modify some small portion of the whole  texture.

Then I draw the modified texture back to the CCRenderTexture *canvas.

Hence, applyShader() will
 * take a texture from CCRenderTexture,
 * create a sprite based on it,
 * apply a fragment shader to it
 * and draw the modified texture back to CCRenderTexture.

This applyShader() will be called repetitively and its code is as follows:

splat = Splat::createWithTexture(art->canvas->getSprite()->getTexture());
splat->renderShader();
art->canvas->begin();
splat->visit();
art->canvas->end();

My shader code is (nothing fancy)

precision mediump float;

varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform sampler2D u_colorRampTexture;
uniform float params[5];

void main() {
    gl_FragColor = texture2D(u_texture, v_texCoord);
    return;
}

So, with the above code I expect the original sprite this to get rendered over and over again without any visual changes. But on each call to applyShader(), the texture is getting stretched a little and the stretched image is getting rendered. After some 10 calls, the image gets so distorted.

Can someone please tell me where I am going wrong?

Thanks :-)

PS: All code shown here is partial, not complete code.

Edit: Adding Screens

Update:
The problem has nothing to do with shaders it seems. It happens even when I dont call renderShader(). The actual lines of code is:

splat = Splat::createWithTexture(art->canvas->getSprite()->getTexture());
splat->setPosition( ccp( art->getContentSize().width * 0.5, art->getContentSize().height * 0.5 ) );
splat->setFlipY(true);
art->canvas->begin();
splat->visit();
art->canvas->end();


texts: Getting a multi-dimensional array of bytes from a Texture2D in unity

texts:
I am currently testing a neural net in Unity, which takes in a very specific configuration of inputs. The input the net takes is (ImageHeight, ImageWidth, 3) in bytes. I am currently trying to do this by reading in the data from GetRawByteData() but the network is not working.

(Before anyone says anything, the network isn't the problem, as I used a different library to handle this on Windows. On Mac (which I am currently working on), this specific library (OpenCVSharp) doesn't work.)

Here was what I tried in Unity:

        Texture2D Image = currenttexture;
        byte[] colors = Image.GetRawTextureData();
        byte[,,,] floatarray = new byte[ Image.height, Image.width, 3];

        int k = 0;
        for (int i = 0; i < Image.height; i++)
        {
            for (int j = 0; j < Image.width; j++)
            {
                floatarray[ i, j, 0] = colors[k];
                floatarray[ i, j, 1] = colors[k+1];
                floatarray[ i, j, 2] = colors[k+2];
                k+=4;
            }
        }

Is there any 'accepted' way to do this, or is there something wrong with my code?


texts: How would I go about implementing fluid dynamics in a game, such as can be seen in this video?