texts: Animating DOM elements vs refreshing a single Canvas

texts:
A few years ago, when the HTML Canvas element was still kinda fresh, I wrote a small game in a rather "unusual" way: each game element had its own canvas, and frequently animated elements even had multiple canvases, one for each animation sprite. This way, the translation would be done by manipulating the DOM position of the canvases, while the sprite animation would consist of altering the visibility of the already drawn canvases. (z-indexes, of course, were the tricky part)

It worked like a charm: even in IE6 with excanvas it showed a decent performance, and everything was rather consistent between browsers, including some smartphones. Now I'm thinking in writing a larger game engine in the same fashion, so I'm wondering whether it would be a good idea to do so in the current context (with all the advances in browsers and so on).

I know I'm trading memory for time, so this needs to be customizable (even at runtime) for each machine the game will be running. But I believe using separate canvases would also help to avoid the game "freezing" on CPU spikes, since the translation would still happen even if the redraws lag for a while. Besides, the browsers' rendering engines are already optimized in may ways, so I'm guessing this scheme would also reduce the load on the CPU (in contrast to doing everything in JavaScript - specially the less optimized ones).

It looks good in my head, but I'd like to hear the opinion of more experienced people before proceeding further. Is there any known drawback of doing this? I'm particulartly unexperienced in dealing with the GPU, so I wonder whether this "trick" would nullify any benefit of using a single, big canvas. Or maybe on modern devices it's overkill (though I'm skeptic about the claims that canvas+js - especially WebGL - will ever be a good alternative to native code). Any thoughts?


texts: How can I ensure a grid can be filled with Tetris-like pieces?

texts:
I'm thinking of making a puzzle game where the objective is to fill a grid with shaped puzzle pieces (for example, the classic Tetris shapes).

How can I go about generating a set of pieces that can be guaranteed to be used to fill the grid, leaving no gaps? How could I adapt this algorithm to scale the difficulty of the resulting puzzle?


texts:
The scenario I am trying to accomplish is attaching a turret to a mount point on a ship.  I have gotten as far as bringing in the prefab and assigning it as a child object with the following code:

GameObject leftFixedGun = (GameObject)MonoBehaviour.Instantiate(Resources.Load("Laser Fixed Gun"), leftMountPoint.position, leftMountPoint.rotation);
leftFixedGun.transform.parent = player.transform;

The problem is, it takes on the rotation of the mount point object, obviously, which isn't exactly what I'm going for.

I have a couple ideas of how to fix this problem, but would really like it to be a different solution all together.

My idea to fix this problem would be to rotate the transform at leftGunMountPoint in order to align the attached gun correctly.

The ideal solution, and the one I would like help with, would to be to align a local mountPoint transform I have under the leftFixedGun to a leftGunMountPoint under the  ship I am trying to attach the gun to.

I hope this makes sense, and if it doesn't please feel free to leave questions in the comments.  Also, please let me know if I am going about this completely wrong =)

Thanks!

EDIT:

Thanks to the answer, and if anyone else is wondering about this, easiest way to accomplish this is as follows:

Create a transform, and line it up with where you want to place the item trying to be mounted.
The following code attached the gun as I wanted.

GameObject laserFixedGun = (GameObject)MonoBehaviour.Instantiate(Resources.Load("Laser Fixed Gun"), leftMountPoint.position, leftMountPoint.rotation);
laserFixedGun.transform.parent = player.transform;


texts: What are vornoi diagrams used for in game development

texts:
I see vornoi diagrams talked about from time to time in the context of game development and graphics, and have seen them used a bit in procedural textures as well as talked about in relation to path finding (I think...).  I kmow vornoi regions are also sometimes used in collision tests, but that isn't quite the same as a vornoi diagrams.

Are vornoi actually used in any actual path finding implementations (I know about A* and variants, navmeshes)?

What else are vornoi diagrams used for in game dev or graphics?

Thanks!


texts: Is it necessary to use texture filtering if I use texture coordinate system?

texts:
I have one question about using texture filtering.
It's clear when I used normalized texuture coordinates (in any API) for example from (0,0) to (1,1) it is necessary to use texture filtering because it's not obvious which pixel should be taken for example at point (0.5, 0.5).

But what in case when I use texture coordinate system. For example I use exact pixel position to assign it to fragment in fragment shader, for example (332,543).
Is it necessary to use texture filtering in that case in order to avoid texture artifacts?


texts:
This is an extension of my previous question.

Recently I had an idea of making an, as I could describe it, agile open-source player-financial-profitable MMORPG, which has an interesting (from my POV) project and development model.

Agile means that development should be iterative, with world extending every fixed period of time. And maybe even game universe\plot may be based on iterative development.

Open-source means that everybody can participate, but, obviously, I wish to establish some kind of core team. I estimate that about 0,01% of players will contribute. And this is where I want to make the number grow to about 0,1%.

That's third part: player-financial-profitable means that every player that has outgrown some reputation ceiling (level or another kind) could contribute some kind of *thing to the game. I think about things as special items for now, but they could be transformed into anything on later architecture stage. Special items can be obtained without any financial donations, of course, but if one player wish to buy it from another, it should be sold for real money, presented as some special "platinum coins" in the game. Money should be parted between solder and creator of the item.

But there is one rule — the item, that one creates, must be unique. Under unique I mean unique. It should have unique look, unique animation, and, most importantly, unique ability, that was not presented by any other item so far, not just exterminator sword with +10000 damage. And unique ability should be coded and designed uniquely. That means, that if creator player is not a one-person collaboration between designer and programmer, he should appeal to off-site labour, or to the core team itself. Working places are created and everybody is happy.

So, that is the model as I see it now (and I invented it yesterday night). The main question is:

1) Should I even bother?
The idea is so ambitious, that could be interpreted as flying in the sky with the help of no wings. And I don't want to spend next ten years of my life (that's the minimum period in which I expect the project to become successful) working on unfortunate from the beginning project.

I have many other questions, but this text already gone too big, so I'll ask only most important:

2) Isn't there some similar game project-model already? I've seen PlaneShift, but they definitely aren't what I'm talking about.

3) Are open-source practices suitable for game development? There are so few good professionals in the field, will they bother to contribute?

4) On how many people should I count on early development stage? Later?

5) How to do all this thing without any reasonable budget?

6) Where do I begin without XP in game development, but with XP in programming per se?

Note to moderators: Please make this community wiki, I don't see my checkbox.


texts: Why does the Debug.DrawRay return these weird lines

texts:
I am working on a small feature of a 2D mobile game where a indicator points towards a object in 2D space. I am trying to make the indicator turn towards the object, however the vector I am trying to construct that points towards the object is off a bit.

When I decided to draw a debug ray from the indicator position to the objects position it was also off a bit. I then decided to draw the debug ray the other way around which gave me a different line. If my understanding is correct, if you switch the starting point and the end point of a ray the line should stay exactly the same right?

using UnityEngine;
using System.Collections.Generic;

public class Tracker : MonoBehaviour {

public GameObject goToTrack;
private List<Renderer> renderers = new List<Renderer>();

void Start(){
    foreach (Transform child in transform) {
        renderers.Add (child.gameObject.GetComponent<Renderer>());
    }
}

void Update () {

}

void OnGUI(){
    Vector3 v3Screen = Camera.main.WorldToViewportPoint(goToTrack.transform.position);

    // if the target is within the viewable screen the indicator shouldn't be rendered)
    if (v3Screen.x > -0.01f && v3Screen.x < 1.01f && v3Screen.y > -0.01f && v3Screen.y < 1.01f) {
        foreach (Renderer renderableObject in renderers) {
            //renderableObject.enabled = false;
        }
    }
    else
    {
        foreach (Renderer renderableObject in renderers) {
            //renderableObject.enabled = false;
        }

        v3Screen.x = Mathf.Clamp (v3Screen.x, 0.01f, 0.99f) -0.04f;
        v3Screen.y = Mathf.Clamp (v3Screen.y, 0.01f, 0.99f) -0.04f;
        transform.position = Camera.main.ViewportToWorldPoint (v3Screen);

        Debug.Log ("Target planet position: " + goToTrack.transform.position.ToString());
        Debug.DrawRay(Camera.main.ViewportToWorldPoint (v3Screen), goToTrack.transform.position, Color.red, 5.0f);
        Debug.DrawRay(goToTrack.transform.position, Camera.main.ViewportToWorldPoint (v3Screen), Color.green, 5.0f);

        //Debug.Log ("Tracker angle: " + angle);
        //transform.Rotate(0,0, angle, Space.Self);
    }

}
}

Output:

UPDATE:
I have noticed that when i substract the second vector with the first vector of the Debug.DrawRay it draws the ray like i want it to.

From this I am taking that the Debug.DrawRay function draws the second vector on top of the first vector. (kind of like the the first vector is Vector(0,0,0) and the second vector is the actual ray you want to draw)


texts: Unity 5 - Accurate logic for 2D projectile deflection

texts:
I'm looking for ideas on how to simulate accurate (as possible) deflection for a projectile moving with a certain velocity in a tile-based 2D game.

The player is able to shoot a projectile to any direction. Right now, I'm casting a ray from the top, bottom, left and right sides of the BoxCollider2D of the projectile and - for example, if the top ray hits a wall - I use Vector2.Reflect to set the new velocity for the projectile (see the upper part of the image).

The problem I'm trying to solve (see the bottom part of the image) happens when the projectile approaches the corner of a BoxCollider2D. That particular situation causes unwanted behavior and I'm thinking of adding 4 additional raycasts (top-left, top-right etc.) for the projectile to check the diagonal collisions (trying it soon).

I'm fairly new to dealing with 2D collision - so I'm interested in hearing about your solutions or ideas, especially if you have dealt with 2D collision / deflection before. Any alternative or more simple solutions are welcome! Maybe this can be done much easier with CircleColliders?


texts:
Newbie here!

I need to know the effective coordinates of a triangle after applying transformations (rotations & translations) to the current (MODELVIEW) matrix.

That is, given a vertex P, I want to calculate, for instance, the new coordinates of P after a rotation of 90º on the x-axis.

How can I do that? Is it also possible to use only OpenGL matrix operations to do this?

Thanks in advance for any tips.

Edit:
The easy one is translation. I implemented it as

#define T(x, v) (x+v)

where I apply T to every coordinate of every vertex.

But what about rotation over a specific axis. Can you please give me some hint?


texts: Drawing a pixel perfrect rectangle with stroke using shader

texts:
I'm drawing a rectangle based on input sizes and use it to mask the screen.
Now I want to give it 1 pixel stroke but it doesn't rasterize to one pixel.
I tried UnityPixelSnap but still no chance.
Here's My Shader:
Shader "MyShaders/Frame"
{
    Properties
    {
        [PerRendererData] _MainTex ("Frame Overlay", 2D) = "white" {}
        framesize ("Frame Sizes", Vector) = (0.5 , 0.5, 0.0 , 0.0) // z & w are just value holders
    }
    SubShader
    {
        Cull Off ZWrite Off ZTest Off Lighting Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float4 color    : COLOR;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 c : COLOR;
                float4 pos : SV_POSITION;
                float4 p : TEXCOORD;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.c = v.color;
                o.p = ComputeScreenPos(o.pos);
                return o;
            }

            sampler2D _MainTex;
            float4  framesize;

            fixed4 frag (v2f i) : SV_Target
            {
                // Base Color
                fixed4 color = i.c;
                float2 screen = i.p.xy;
                float2 screenSize = _ScreenParams.xy;

                // Get Pixel Size
                framesize.z =  (1.0f  /  screenSize.x);
                framesize.w =  (1.0f /  screenSize.y);

                // Draw Stroke
                if(screen.x > (0.5f - (framesize.x/2) - framesize.z) && screen.x < (0.5f + (framesize.x/2) + framesize.z)
                    && screen.y > (0.5f - (framesize.y/2) - framesize.w) && screen.y < (0.5f + (framesize.y/2) + framesize.w))
                color = float4(1.0, 1.0, 1.0, 0.4f);

                // Delim Using Ratios
                if(screen.x > (0.5f - (framesize.x/2) - framesize.z*.2) && screen.x < (0.5f + (framesize.x/2) + framesize.z*.2)
                    && screen.y > (0.5f - (framesize.y/2) - framesize.w*.2) && screen.y < (0.5f + (framesize.y/2) + framesize.w*.2))
                color.a = 0;

                // Apply UI Alpha
                color.rgb *= color.a;
                return color;
            }
            ENDCG
        }
    }
}

It should be assigned to a full width/height panel in a canvas.
This is what happens :

I've found this useful shader, It works perfect but I have no idea how can I use it in my shader.
I'll be very greatful if someone know how to make it work :)


texts:
I am trying to draw a 3D model I made with Blender in Monogame/XNA and this is the result I get when I draw 2 of them on top of each other

How can I make it so that the colors don't add up, but the one covers the other ? Here is my drawing code:

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);
    Vector3 modelPosition = new Vector3(-2500, 1500.0f, 0.0f);
    Vector3 cameraPosition = new Vector3(0.0f, 0.0f, 5000.0f);
    float aspectRatio = (float)graphics.GraphicsDevice.Viewport.Width /
          (float)graphics.GraphicsDevice.Viewport.Height;
    Vector3 scale = new Vector3(1f, 1, 1);
    Matrix[] transforms = new Matrix[Brick.Bones.Count];
    Brick.CopyAbsoluteBoneTransformsTo(transforms);
    foreach (ModelMesh mesh in Brick.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index]*Matrix.CreateScale(scale)*
           Matrix.CreateRotationY(modelRotation)*Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                  MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
        }
        mesh.Draw();
    }
    base.Draw(gameTime);
}


texts:
I am trying to allow players of my game to remap the controls (eventually from the menu). Currently, some of the buttons have been defined, but they can't be changed. They are hard-coded. For example, this is how I handle key events now:

    switch(e.getKeyCode())
    {
        case KeyEvent.VK_A:
            ...
            break;
        case KeyEvent.VK_D:
            ...
            break;
        ...et cetera...
    }
}

How can I build a system that allows the actual keys for various actions to be remapped by the user?


texts: Has anyone tried using one of those BAAS providers to create mobile games?

texts:
I'm hearing a lot about different companies offering back-end as a service (BAAS) for mobile apps but it seems like none of them are very successful with mobile games. Is there any reason why not outsource the server to a provider.

The premise here is that the game does need a back-end to implement multiplier ans social functions.


texts: color individual triangles on a mesh in Unity?

texts:
I am trying to use Unity to display a model and color some triangles on the model to high light those parts of the model.

I have created a scene, with a camera, a light source and a cube.
After the scene loads I have a script on the cube where I am importing a new mesh and replacing the cube mesh with the new mesh. I am also giving each triangle a random color.

    void Update () {
    if (Time.time > 10 && newShapeLoaded)
    {
        System.Collections.Generic.List<facet> newModel = readStl(@"C:\testing1\stls\sphere.stl");
        System.Collections.Generic.List<Vector3> vertices = new System.Collections.Generic.List<Vector3>();
        foreach (facet f in newModel)
        {
            vertices.Add(f.vecA);
            vertices.Add(f.vecB);
            vertices.Add(f.vecC);
        }
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        mesh.vertices = vertices.ToArray();
        int[] t = new int[vertices.Count];
        Color32[] colors = new Color32[vertices.Count];
        Color32 currentColor = new Color32();
        for (int i = 0; i < vertices.Count; i++)
        {
            t[i] = i;
            colors[i] = currentColor;
            if (i % 3 == 0)
            {
                currentColor = new Color(
                                    Random.Range(0.0f, 1.0f),
                                    Random.Range(0.0f, 1.0f),
                                    Random.Range(0.0f, 1.0f),
                                    1.0f);
            }
            colors[i] = currentColor;
        }
        mesh.triangles = t;
        mesh.colors32 = colors;
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        mesh.UploadMeshData(true);
        newShapeLoaded = false;
    }
}/* Update() */

This was not working and searching I found I needed to change the material type to a material that uses vertex color shading. I found the Particles>VertexLit Blended Shader colors the triangle but then the triangles are drawn in the wrong order so the shape appears inside out.

Is their anyone that knows more about Unity and 3D that could give me some advice or let me know where I have gone wrong with this?

(edit)
So I have investigated this further and I believe the comment made about the particle material being the reason for the shape appears inside out is correct.

I also noticed that the original cube has this problems before I change the mesh as well.
So I have tried to find a material with a shader that will still let me color the triangles but not break the render order of the triangles. Unfortunatly I haven't been able to get anything to work.
I have found a thread here where several people have tried to create a shader to do this and I have downloaded their projects and run them and tried to get them to work with very limited success. This lead me to also find several tutorials on shader programming to try and understand what was happening, but these have not given me any better understanding of how to get vertex coloring working.

I am now wondering if I have gone off track because all I really want to do is to make a simple model and change the color of some triangles on the model. I though this would be like a simple hello world exercise for 3D graphics, but I have put over a week into this now and tried several different approaches and still have not been able to get this working.

I would be very grateful if someone could show me an example of changing colors of triangles on a mesh? Or if someone that understands 3D graphics could just point me in the right direction to a tutorial or guide that will help me learn what I need to know to get this working and let me know if this is the correct way to try and be able to change colors on a mesh?


texts:
Previously, I had a problem with my frustum culling producing too optimistic results- that is, including many objects that were not in the view volume. Now I have refactored that code and produced a cull that should be accurate to the actual frustum, instead of an axis-aligned box approximation. The problem is that now it never returns anything to be in the view volume.

As the mathematical support library I'm using does not provide plane support functions, I had to code much of this functionality myself, and I'm not really the mathematical type, so it's likely that I've made some silly error somewhere. As follows is the relevant code:

class Plane {
public:
    Plane() {
        r0 = Math::Vector(0,0,0);
        normal = Math::Vector(0,1,0);
    }
    Plane(Math::Vector p1, Math::Vector p2, Math::Vector p3) {
        r0 = p1;
        normal = Math::Normalize(Math::Cross((p2 - p1), (p3 - p1)));
    }
    Math::Vector r0;
    Math::Vector normal;
};

This class represents one plane as a point and a normal vector.

class Frustum {
public:
    Frustum(
        const std::array<Math::Vector, 8>& points
        )
    {
        planes[0] = Plane(points[0], points[1], points[2]);
        planes[1] = Plane(points[4], points[5], points[6]);
        planes[2] = Plane(points[0], points[1], points[4]);
        planes[3] = Plane(points[2], points[3], points[6]);
        planes[4] = Plane(points[0], points[2], points[4]);
        planes[5] = Plane(points[1], points[3], points[5]);
    }
    Plane planes[6];
};

The points are passed in order where (the inverse of) each bit of the index of each point indicates whether it's the left, top, and back of the frustum, respectively. As such, I just picked any three points where they all shared one bit in common to define the planes.

My intersection test is as follows (based on this):

bool Intersects(Math::AABB lhs, const Frustum& rhs) const {
    for(int i = 0; i < 6; i++) {
        Math::Vector pvertex = lhs.TopRightFurthest;
        Math::Vector nvertex = lhs.BottomLeftClosest;
        if (rhs.planes[i].normal.x <= -0.0f) {
            std::swap(pvertex.x, nvertex.x);
        }
        if (rhs.planes[i].normal.y <= -0.0f) {
            std::swap(pvertex.y, nvertex.y);
        }
        if (rhs.planes[i].normal.z <= -0.0f) {
            std::swap(pvertex.z, nvertex.z);
        }
        if (Math::Dot(nvertex - rhs.planes[i].r0, planes[i].normal) < 0.0f) {
            return false;
        }
    }
    return true;
}

Also of note is that because I'm using a left-handed co-ordinate system, I wrote my Cross function to return the negative of the formula given on Wikipedia.

Any suggestions as to where I've made a mistake?

Edit: I changed my intersection test somewhat. No change, though.


texts: What's the purpose of layers in map editors?

texts:
I have a question regarding map editors, like Tiled, for example.
I am currently making my own map editor, and I wondered if someone could explain to me what is the purpose of layering in tiled for example.
What purpose does it serve in creating a map?


texts: Generating skeleton bind pose from vertex weights

texts:
Assuming that you know how many bones should be in the skeleton, and you have the bone hierarchy, is it possible to calculate the bind pose of the bones just based on the vertex weights?

To elaborate it a bit, let's say you have a skinned mesh, and each vertex of this mesh has 4 weights (at most). So you have 4 weight values and 4 bone ids for each vertex. Also let's say you have a skeleton with 10 bones, and all you have is the bone hierarchy. You need to position the bones to match the mesh (bind pose).

I am wondering if this can be done just using the weights/bone ids?


texts: Xna custom mouse not allowing me to move its sprite past certain bounds

texts:
I have written a Custom mouse, with a Custom sprite, using MouseState, and getting the X and Y variables. However i also have a camera that i wrote, and this allows me to leave the initial box. One sprite that can freely move this area, but my mouse gets stuck in a box that seems proportional to my screen resolution some times.

  //This is where i create the Texture, Vector and MouseState of the Custom Cursor
Texture2D Mouse_texture;
MouseState mouse_state;
Vector2 Mouse_pos;

  // This is my Resolution and i have IsFullScreen = true
graphics.PreferredBackBufferWidth = 1600;
graphics.PreferredBackBufferHeight = 900;

  // Loading the Texture
Mouse_texture = Content.Load<Texture2D>("mouse");

  // Getting the current mouse State this is in the update function
mouse_state = Mouse.GetState();

  // How i set the mouse position Simple Vector2 stuff and i never do anything else
  //   to handle the the position of the mouse
Mouse_pos = new Vector2(mouse_state.X, mouse_state.Y);

  // and this is me Drawing it
spriteBatch.Draw(Mouse_texture, Mouse_pos, Color.White);

If you need any more code let me know


texts: How do people implement pathfinding movement?

texts:
I understand how A* works, but I don't understand how movement is implemented, e.g. creating a list of directions and then going through that list until every direction is empty. How does that work?

EDIT: Node based.


texts: Third Person - Highlight "Usable" Objects

texts:
I'm trying to figure out a good solution in a third-person RPG to determine if the character is facing and close enough to an object for it to highlight and be shown as a usable item - a door, or a chest, or any other usable object in the scene.

I imagine the best approach is ray-casting, but I've yet to figure out how this would actually work.  I plan to have a usable script on all usable objects that defines what happens during use (a door or chest opens, a coin goes into your inventory, etc), but I need to know whether the player can use the item, highlight it, and also determine which object is the "best choice" based on facing direction and distance if multiple items are in range.


texts: Server related questions and it is available options?

texts:
i went thru a lot pages here searching for information about the "server side" of a multiplayer game, while i did found some information they were not exactly what i was looking for.

What is the best available options
for the server communication ?
Is it worthed to handle a game server with website requests for a mmo or should not even be consider at all ?
Are you aware of any good material
regarding the same in C# for a
headstart on the subject ?
When should i consider creating multiple servers for example "monsters servers, world drop data and the such" or what should i consider for this (i've seen that some very popular games out there use this sort of thing such as a server for monsters, lineage for example) ?

  Currently i am developing a 2D game
  using Tiled and C# for single player
  but i would like to further turn it
  into a mmo game but i am very unsure
  of what a server would look like for
  this ... Any further knowledge or
  personal experience you could provide
  related to the server aspect and
  options i would appreciate.

  As i said above it is a 2D with
  multiple maps where the user goes
  around as their level grows, each map
  which is not a town has monsters
  spawning and despawning when killed by
  players, players can move around on
  the possible spaces, once a player
  hits the border of the map at defined
  locations it will take them to the
  next map...

  Since i am doing it on a 800x600 size
  i guess i will need to limit the
  players per server (or something like
  world's or whatever term is used for
  it..) so it does not over populate the
  screen with players ...

if my question or english at any point is not good please wrap your comment and i will try to rework it to best fit the community of if you can edit it and correct what you feel like should be changed, please go ahead...


texts:
Where can I learn how to do simple 2d animation well? Or is it really just literally drawing every single frame of something in photoshop? Is there tips or tricks? Tutorials to help get started?

Also, what software options are there (preferably open source or even just free)?


texts: Do game-theoretic considerations stand in the way of this market-based game-mechanic achieving its goals?

texts:
Mechanic

The mechanic is called "market manipulation" and is supposed to work like this:

Players can enter the London Stock Exchange (LSE)
LSE displays the stock prices of 8 to 10 companies and derivatives. This number is relatively small to ensure that players will collide in their efforts to manipulate the market in their favor. The prices are calculated based on

real world prices of these companies and derivatives (in real time)
any market manipulations that were conducted by the players
any market corrections of the system

Players can buy and sell shares with cash, a resource in the game, at current in-game market value
Players can manipulate the market, i.e. let the price of a share either rise or fall, by some amount, over a certain period of time. Manipulating the market requires spending certain in-game resources and is therefore limited.
The system continuously corrects market manipulations by letting the in-game prices converge towards their real world counterparts at a rate of 2% of the difference between the two per hour. Because of this market correction mechanism, pushing up prices (and screwing down prices) becomes increasingly difficult the higher (lower) the price already is.

Goals

Players are supposed to collide (and have incentives to collide) in their efforts to manipulate the market in their favor, especially when it comes to manipulation efforts by different groups.
Prices should not resolve around any equilibrium points. The more variance the better.
Band-wagoning should always involve risk (recognizing that prices start rising should not be a sure sign that they will keep rising so that everybody can make easy profits even when they don't manipulate the market themselves)

Question

Are there any game-theoretic considerations that prevent the mechanic from achieving these goals?


texts: Unity2D: How to save volume of audio source when game is restarted?

texts:
How do I save volume of my audio source (clicking the mute button) when game is restarted. You see I have one scene in my game and once the player dies there is a button the user can click on that resets the game, however it also resets the audio source, so when I play the game and click my mute button, the audio source volume is at 0 but when I die and click the reply button (the restart/reset button) the music is restarted as well, instead of staying muted (save the current volume). I tried using DontDestroyOnLoad(this) but my muted script is attached to my game over panel animation (the panel comes down when player dies) making the my game over panel animation not being destroyed when you restart the game. I tried other methods like putting my mute button script on a parent empty object and putting the object that has the audio source on under it as a child but it did the same thing.
Anyway this is my mute button script:

private bool mute;

public void Muted ()
{
    mute = !mute;
    if (mute){
        gameObject.GetComponent<AudioSource>().volume = 0;
    }else
    {
        gameObject.GetComponent<AudioSource>().volume = 1;
    }
  }
}

And this is my restart level when button is pressed (p.s. I used the OnClick method activating methods):

public void NavigateTo(int scene)
{
    Application.LoadLevel ("Game Level");
}

Thank you in advance :)


texts: Moving inventory items around causes reference problems

texts:
I'm in the process of implementing an inventory system in my game.

The script which is most important to this question is InventorySlotManager.

public class InventorySlotManager : MonoBehaviour
{
    ItemData itemData;

    const int numSlots = 20;
    Item[] itemsInInventory = new Item[numSlots];
    [SerializeField] GameObject[] slots = new GameObject[numSlots];
    [SerializeField] GameObject itemImagePrefab;
    int[] stackSize = new int[numSlots];

    void Awake()
    {
        itemData = GameObject.Find("Item Manager").GetComponent<ItemData>();
    }

    void Start()
    {
        AddItem(itemData.coin);
        AddItem(itemData.silverRing);
        AddItem(itemData.coin);
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.Alpha1))
        {
            AddItem(itemData.coin);
        }
        if (Input.GetKey(KeyCode.Alpha2))
        {
            AddItem(itemData.silverRing);
        }
    }

    void AddItem(Item item)
    {
        int indexOfDuplicateItem = System.Array.IndexOf(itemsInInventory, item);

        if (indexOfDuplicateItem > -1)
        {
            Text quantityTextOfDuplicateItem = slots[indexOfDuplicateItem].transform.Find("Item Image(Clone)").gameObject.GetComponentInChildren<Text>();
            quantityTextOfDuplicateItem.text = (++stackSize[indexOfDuplicateItem]).ToString();
        }
        else
        {
            for (int i = 0; i < numSlots; i++)
            {
                if (itemsInInventory[i] == null)
                {
                    itemsInInventory[i] = item;
                    GameObject itemImage = Instantiate(itemImagePrefab, slots[i].transform);
                    itemImage.GetComponent<Image>().sprite = item.itemSprite;
                    Text quantityTextOfNewItem = slots[i].GetComponentInChildren<Text>();
                    stackSize[i] = item.itemQuantity;
                    quantityTextOfNewItem.text = stackSize[i].ToString();
                    return;
                }
            }
        }
    }
}

This does what you'd expect. (The bit in Update is just there temporarily for testing.) When an item gets added, the function checks to see if one already exists in the items array. If not, then the for loop is executed and the item is added to the items array, an item image game object is instantiated in the corresponding index of the slots array, etc. So far so good, everything behaves properly until I start dragging items around in my DragHandler script.

So I press play, my inventory has two kinds of objects in it (coin, and silver ring). They each display their correct quantities (stack sizes) as I keep adding items. Then, I move the coin from slot 0 to slot 5 and attempt to add more coins to the inventory. It stops working because the line Text quantityTextOfDuplicateItem = slots[indexOfDuplicateItem].transform.Find("Item Image(Clone)").gameObject.GetComponentInChildren<Text>(); returns null at that point.

What is the best way to fix this such that this reference won't become null if I move the item to a different slot after it gets added to my inventory? I think I either have to map the items array to the slots array or store all of these values, e.g., items, slots, quantitytext, in one array. Is this correct?


texts: How to determine the demographics of a game after release?

texts:
I am interested in demographics of people who actually play my game. Here are few assumptions I made:

Players, especially the younger ones, are often not the buyers (or downloaders in case of freemium) and I don't think I can get data about buyers anyway
Games targeted to a certain audience can be played by completely different group in the end (Pokemon vs. Call of Duty)

The closest I can get is to probably get a similar game that already has demographics data. But how did they get the data?

I have read the following questions:

Other than the ESA are there other sources for demographic data?
Casual gamer age distribution

These questions give me some data, but not the way how were the data obtained. Also some of the links are already invalid.


texts: Unity 2D Game: Camera following target and looping stage

texts:
I'm with a problem and I need some help, because I'm on early learning of gaming and Unity, and i want to learn doing it, so, i need all the help, you developers know how each little help, helps a lot!!

I found the answers of these questions in here, but they don't work properly together or i don't understand it how it works to put it on my code;

I'm building a mobile game and i need the camera to follow the character, i found how to do it, but the thing is: the stage is a 4:3 kinda stage, that repeats again and again and again(well, that's the idea, i still don't know how i do this), but, when the player goes to the groud, the camera is still centered on the character, so it continues following it, but there's no more stage, then nothing appear in there, but i want the camera to doesn't follow the character when it's already on the Y border of the stage. Can someone light me with the google searching with this?

Exactly like this:
https://www.youtube.com/watch?v=ETxoUDWCBvE

And how i can do the stage repeat in a looping? I though in make the scenario move instead of the character then make it loop with a technique i saw in some Flappy bird clone video, but i don't know how the camera would work.

I want to know how i can start doing these.

Thanks.

Ps: Unity 5 ;-;

That's what happen with the camera:


texts: Rendering into every material preview windown. How is this possible?

texts:
So starting up unity today  has presented me with a extremly wierd bug. The animated material that is rendered by the NVidia HairWorks Integrationg seems to be rendering into every material preview window.
I have not done anything special to "achieve" this. Restarting Unity does not help( I tried all the usual stuff). The fur even simulates inside the material preview window if I hit the little play button. Any ideas ?


texts: Smooth shading along edges with duplicate vertices

texts:
On this generated mesh, I have sharp edges, because each square has duplicate vertices separate from its neighbours.
I can't remove the duplicate vertices because I'm using them to provide unique UV texture coordinates on each square. If I share the vertices then the texture wraps around the surface in an unwanted way.
Is there a way I can get smooth shading along these edges, even without shared  vertices?


texts: Libgdx Box2d createfixture crashes vm intermittently

texts:
I have a hard to debug problem.  I have a Box2D game which creates a wheeled vehicle.  I want the vehicle body to reflect when it goes from moving left to moving right.  to do this i set a flag in a changelistener on a button and then in update method i destroy and recreate the body facing the other way.  it works fine most of the time but if i flip the vehicle several times quickly JVM crashes.  no errors nothing in log.

i added system.out.prints and the errors occur in the routine that instantiates the new body and before anything gets deleted/removed so i don't think the UI is trying to access null pointers.  and if it was it should throw an error.
 M
the crash seems to be at createFixture statements.  but the work most of the first time. I tried debugging but the error doesn't happen much when the flips are slow.  in any case createFixture drops fairly quickly into jni.

Is this a Box2D bug?  Is GC the issue?  From Mission Control I see the GC is collecting on a period of ooh maybe 5s and flipping slower than that mostly works.

how do i debug this?

i am win7 64bit with 64bit at and jdk7 64bit.  libgdx-0.9.9 and sometimes libgdx-nightly-20140215.


texts: 2D animations frames vs 3D animation for small indie project: timing considerations

texts:
pretty lame question but was wondering..

I am developing a 2D game using Cocos2D for iOS. The art work till now is all 2D (is a shooter game) but some of the characters would benefit of complex animations (eg. 20 frames). I feel a bit stupid because I came across only now that there is the chance to do 3D to 2D frames exporting and then to use them in Cocos2D.

The thing that put me off on 3D gaming at first was that it takes more than one person in a team to do so properly (Illustrator, 3D modeller, 3D animator and programmer). Now I feel a bit stupid because having a 3D model I could do and modify the poses whenever I wanted (I should ask to the 3D animator which I guess would be time expensive).

Instead now is me and two illustrators (as I require many frames per character).

Is my impression that it would have been much longer right or not? Are there any other project management considerations that can be done on this?

Sorry if for some this might be trivial but is my first "indie game developer experience".


texts: Tracking player location in realtime 2d mmo

texts:
I have read all of the answers here about tracking player locations, but still have some questions. I don't seem to understand how to do this efficiently, and feel that the internet could greatly benefit from an effective solution that is easy to find.

Anyway, I am making a 2d mmo (the first multiplayer game I have made that will handle this many people) and can't seem to come up with a good way to manage the location of players, and alert other players when they are near them. My map is tile-based, and I want the clients connected to know when a player of another client is withen 200 blocks from the other client.

My map uses x and y coordinates, and each block is a value. I read something I was linked to by a similar question here, that explained that a good way of managing this sort of thing is to create a box around each player, and to alert both player's when their boxes overlap (assuming I understood it correctly).

But how should I create these boxes without wasting tons of computing power and resources? I thought of storing it in SQL database, but that would be too slow. I then realized that player locations would have to be stored in the RAM. So what are some previously used strategies to track player movement in the RAM? Should I store a variable for each player containing the coordinates withen 200 blocks from them, and constantly have the server checking to see if two players overlap? This doesn't seem very efficient, and I believe that I am going about this the wrong way.

Any help is greatly valued.


texts: Why does the engine crash when I POST data to a server?

texts:
I am working on communications between my game and a cloud database. I'm working on the authentication part but when I try to pass data to the server in a POST the engine crashes. If I pass in a simple string like "username" it does not crash and I get an error response from the server as expected. But when I try to pass in a JSON string the engine crashes. Here is my code:
OnAuthCookieResponse = cookieResponseDelegate;
TSharedRef<IHttpRequest> request = FHttpModule::Get().CreateRequest();
FString url = NewObject<UURLBuilder>()
     ->Host(BASE_URL)
     ->Path(SESSION)
     ->Build();

request->SetURL(url);
request->SetVerb("POST");
request->SetContentAsString("{\"username\":xxxxxxxx}");
request->OnProcessRequestComplete().BindUObject(this, &UAClass::ReceivedAuth);
request->ProcessRequest();

The stack trace points me to line 559 in CurlHttp.cpp. IsURLEncoded() returns false which causes the check() to fail.
check(!GetHeader("Content-Type").IsEmpty() || IsURLEncoded(RequestPayload));

However when the engine passes data here, IsURLEncoded() returns true and the check() passes. Here is a sample of some data from the engine that passes. You can see it is a JSON string.

Here is what my data looks like that causes the engine to crash

You can see they are both JSON strings but mine causes the check to fail. I have also tried to completely URL encode the JSON string and the check still fails.
So why does this fail for me but passes when used by the engine?


texts:
I've tried to apply a Pixi filter to a image and save it to cache but the image doesn't get saved with the filter.

colorMatrix = new PIXI.ColorMatrixFilter();
colorMatrix.matrix = [0,0.0,0.5,-0.2, 0,0,1.0,-0.2, 0.0,0.0,0.5,-0.2, 0.0,0.0,0.0,1]
image = game.make.bitmapData()
image.load("testImage")
image.filters = [colorMatrix]
game.cache.addBitmapData("testImageWIthFilter", image);

Is it not possible to save it to cache? The only thing I see is the original image when using the code down below:

messageImage = game.add.sprite(0, 0, game.cache.getBitmapData('testImageWIthFilter'))


texts:
I'm making an RPG game system and I'm having a hard time deciding on doing detailed or abstract character statistics.  These statistics define the character's natural - not learned - abilities.  For example:

Mass Effect: 0 (None that I can see)
X20 (Xtreme Dungeon Mastery): 1 "STAT"
Diablo: 4 "Strength, Magic, Dexterity, Vitality"
Pendragon: 5 "SIZ, STR, DEX, CON, APP"
Dungeons & Dragons (3.x, 4e): 6 "Str, Dex, Con, Wis, Int, Cha"
Fallout 3: 7 "S.P.E.C.I.A.L."
RIFTS: 8 "IQ, ME, MA, PS, PP, PE, PB, Spd"
Warhammer Fantasy Roleplay (1st ed?): 12-ish "WS, BS, S, T, Ag, Int, WP, Fel, A, Mag, IP, FP"
HERO (5th ed): 14 "Str, Dex, Con, Body, Int, Ego, Pre, Com, PD, ED, Spd, Rec, END, STUN"

The more stats, the more complex and detailed your character becomes. This comes with a trade-off however, because you usually only have limited resources to describe your character. D&D made this infamous with the whole min/max-ing thing where strong characters were typically not also smart.

But also, a character with a high Str typically also has high Con, Defenses, Hit Points/Health. Without high numbers in all those other stats, they might as well not be strong since they wouldn't hold up well in melee combat. So things like that force trade-offs within the category of strength.

So my original (now rejected) idea was to force players into deciding between offensive and defensive stats:

Might / Body
Dexterity / Speed
Wit / Wisdom
Heart
Soul

But this left some stat's without "opposites" (or opposites that were easily defined). I'm leaning more towards the following:

Body (Physical Prowess)
Mind (Mental Prowess)
Heart (Social Prowess)
Soul (Spiritual Prowess)

This will define a character with just 4 numbers. Everything else gets based off of these numbers, which means they're pretty important. There won't, however, be ways of describing characters who are fast, but not strong or smart, but absent minded. Instead of defining the character with these numbers, they'll be detailing their character by buying skills and powers like these:

  Quickness
  Add a +2 Bonus to Body Rolls when Dodging.

for a character that wants to be faster, or the following for a big, tough character

  Body Building
  Add a +2 Bonus to Body Rolls when Lifting, Pushing, or Throwing objects.

What are some pitfalls with a small stat list and a large amount of descriptive powers? Is this more difficult to port cross-platform (pen&paper, PC) for example? Are there examples of this being done well/poorly?


texts: What would be the simplest way to create a 2D board game for Android?

texts:
I'd like to create a very simple 2D board game for Android, it would be a concept/mockup so I can see how the game works out.

Let's for the sake of this question that it's a clone of Othello - board game with score display, clickable game pieces/spots on a square grid and some animations.

I have to choose from these approaches:

do it all myself, draw the game on Canvas - I've done one game this way, and it took some time to code it. Then, that was a casual action game and the animations would be hard to implement.
implement it with Android widgets - I'd use RelativeLayout/TableLayout; the pieces will be ImageViews - this way I'd get the animations for free with Android tween animations. This would be the quickest of all solutions timewise, but I might run into some problems that may be a deal breaker.
use AppInventor - it may do the task, but don't know anything about it, this approach would also require some time to go through the tutorials.
use a proper game engine. That will take time to learn how to use it, which I view as the biggest disadvantage as I do mostly business apps, not games. And I don't know which one to choose from.

I really only want to throw this together in the shortest amount of time to see how it works, so I don't want to invest a lot of time to do it in the most "correct" way - that I'll do later if the concept works.


texts: How to resize an image loaded using ContentManager in XNA

texts:
I am new to XNA programming and I loaded the background image using ContentManager as a Texture2D object.

The background image which I have is of size 480*320. I have kept the minimum game window size as 640*480. My question is how would i resize the background image to the size of the game window.

Thanks in advance!


texts: How to implement 3d maneuver gear physics in unity?

texts:
I am trying to create a attack on titan styled game for a school project. I am not new to programming, but I am new to game development. I couldn't find any resources for this, hence I am posting it here.

How do I go about implementing 3d maneuver gear physics from attack on titan anime?

What is it?

In case you don't know, here's a brief link about 3d maneuver gear.

A brief commentary about 3dMG

It's basically a grappling hook based system (similar to what you would find in a spiderman game), but it has different components to it, which makes it quite complex to think about.

My Approach so far

I have seen tutorials on how to use hooks in unity and stuff, but it would be great if someone could give me a general idea as to how to even start with this kind of thing. I would appreciate your answer, even though it is not unity specific.

The idea is to have two points on the character, from where we fire the ropes. These ropes could simply be graphics (or unity's RaycastHit). And then we would also need information about the hook "hit point". Once we know that, we just reel in ourselves towards that. However the problem is that I don't know how to use momentum etc to effect the character's movement. Also since it's not just one rope(like a spiderman's game), but two, it's even difficult to think as to how would the movement be if user uses only left hook, or right hook or both. Also there is this gas aspect, which would propel you further and it should also be taken into account, along with momentum that we would carry.

So any general idea would be greatly appreciated.


texts: How can I create straight, glowing lines?

texts:
What techniques are used in this style?  What steps would be required to recreate it?

(Screenshot of this app: https://play.google.com/store/apps/details?id=com.dkeesto.holographlw)


texts: Incorrect colour blending when using a pixel shader with XNA

texts:
I'm using XNA 4.0 to create a 2D game and while implementing a layer tinting pixel shader I noticed that when the texture's alpha value is anything between 1 or 0 the end result is different than expected.

The tinting works from selecting a colour and setting the amount of tint.  This is achieved via the shader which works out first the starting colour (for each r, g, b and a) :

float red = texCoord.r * vertexColour.r;

and then the final tinted colour :

output.r = red + (tintColour.r - red) * tintAmount;

The alpha value isn't tinted and is left as :

output.a = texCoord.a * vertexColour.a;

The picture in the link below shows different backdrops against an energy ball object where it's outer glow hasn't blended as I would like it to.  The middle two are incorrect as the second non tinted one should not show a glow against a white BG and the third should be entirely invisible.

The blending function is NonPremultiplied.

Why the alpha value is interfering with the final colour?


texts:
What relationship is there, if any, of "materials" and vertex/pixel shaders (or the "effects" that combine the latter two)?

I have the impression that before the advent of HLSL, materials were explicitly handled by Direct3D or OpenGL.  I also have the impression that with HLSL, many prior effects are now handled directly (and generically) via the rendering pipeline in vertex/pixel shaders.  In other words, I hae the impression that materials are often little more than what DirectX would call an "Effect."  If so, this means that many models that specify materials would be transformed by a content pipeline into an "Effect".

Is this correct?  Where can I get a little more history/info that either corroborates or corrects the impression I have?


texts: How to switch sprite animations in cocos2d-x?

texts:
I have a "GameCharacter" class where I have a sprite for my main character in the game, I loaded the frames and animations correctly. I can switch between animations with single touches or swiping gestures. Right now I can rotate between animations.

In my touch funtion of my scene I have this:

_mychar->RunAnimation(id);

where id is the ID of the animation, just an integer I change with every touch.

the method works like this:

void GameCharacter::RunAnimation(int a){

    _sprite->stopAllActions();
    if(a<_animation.size() && a>=0){
        _sprite->runAction( CCRepeatForever::create(_animation[a]));
    }
}

_animation[] is just a vector with CCAnimate* objects retained (I release them later when I destroy the GameCharacter).

I have 2 idle animations, I want to switch between them randomly, for example, I want to "queue" the first animation 3 to 5 times and the second 1 to 2 times, and repeat like this forever... also, I want to interrupt this "infinite random idle animation" with a touch that makes the character run another animation until it ends (for example a jump animation) and when it ends, just get to the idle animation. I don't know if I explained well, I hope you can understand me.

The id for the animations are:

0-idle1 (3 frames)
1-idle2 (6 frames)
2-jump (12 frames)
3-walk (12 frames)

Right now, i just need to be able to get the character in that idle state (random times between animations 0 and 1) and whenever touch, the jump animation is done once and at the end the idle start again...

I will solve the walking animation later.

Thanks in advance!


texts: Implementing unlockable items on Android

texts:
I know this would be a beginners question (some of you might think) but I would like to know different approaches for this.

I have a game with lets say 20 unlockable items, at the main menu I have a button where the user can go to an activity and view the unlockable items. So I would like for it to have a "Locked image" and under it a text telling you what the item is and maybe how to unlock it.

What is the best way of going about this?

And then when the item is unlocked during the game, maybe put a variable in the shared preference and check at the beginning of the activity with the unlockabled items.

Let me know what you guys think. Thanks.


texts: Calculating 2D (screen) coordinates from 3D positions in XNA 4.0

texts:
I have a program that draws some items to the scene by loading their positions from a file. Now I want to place a Ray on the same location where the items are drawn. So my question is how can I calculate the position of the ray (it's 2D components) by using 3D coordinates of each particular item? The items don't move anywhere, so once they are placed they stay until the end of the programs execution.
 Thanks.


texts: Quadtree vs multiple resolution grids for terrain rendering

texts:
I have been thinking about quad trees with regards to terrain rendering.

From my understanding the basic functionality of quadtree terrain rendering is to frustum cull the terrain in such a manner:

function render() {
    lod_threshold++;
    if(lod_threshold_reached || !has_children()) {
        draw_terrain_mesh();
        return;
    }
    for(child in children) {
        if(child.bounds.intersect(viewing_frustum)) {
            child.render();
        }
    }
}

where node.bounds is a 3d bounds calculated as containing the maximum heightmap value of the contained terrain

My questions are the following

If we are in fact testing a 2d portion of terrain with it's bounds calculated to include the maximum heightmap value against the 3d frustum, what is the preferred bounds calculation for generating the node.bounds in the quadtree?
That a tree is necessary because that one has to iterate every portion of a 3d scene to calculate frustum occlusion in a general way. Eg, there is no shortcut algorithm to calculate the set of 3d cells generated from a 2d grid that intersect the viewing frustum. As a more general question and to question the obvious, is there a way to calculate cells in a viewing frustum without having to iterate every cell in a scene? Presumably not otherwise you wouldn't need trees for culling

With regards to an alternative grid implementation:

Has this implementation been contemplated for general purpose terrain culling? I am presuming that some form of grid base terrain culling is certainly preferred in certain games, namely top down games where the possibility of terrain in the distance of being on camera is non-existent.

function calc_cells_in_quadrilateral(frustum_projection_onto_2d_terrain_grid) {
    //calculate cells in the resulting quadrilateral projection of the frustum onto the grid without having to bounds test every cell
    //at some point based on distance from camera, assign lod
}
retrieve lod for each cell in the calculated set from lod grids
have multiple (array2 or intmap) containing the terrain data at every lod for O(1) retrieval

Is there is a way to calculate cells in a quadrilateral without having iterate every cell in a grid? eg, from shaving off cells from slopes or something?
If there is, in what fashion should one assign the lod cell based on distance? I haven't contemplated this in detail because #1 may be impossible
The terrain would not be optimally culled in this 2d culling algorithm against the quadrilateral frustum projection onto the heightmap, because the height value at the edges may be outside the screen, correct?
http://www.olhovsky.com/2011/03/terrain-started/ In this post, he describes assigning lod from a grid and from a quad tree. The illustrations are confusing with regards to whether question #1 is correct and terrain rendering with quad trees serves to draw the terrain mesh against the frustum as opposed to just as a function of distance 360 around the camera as at appears to do with his grid implementation. Please specify whether it appears that he is infact not frustum culling in the grid implementation but is frustum culling the quadtree.


texts: Load state / continue game based on user input

texts:
I'm working on a rather simple 2D game, with a pretty small set of values that will need to be preserved for a user to pick up where they left off last time they played.

Rather than saving/loading the state of the game for users to leave/return, I'm considering something akin to what MegaMan did, where a user enters a "password" to resume from their previous state, like so:

How is something like this generally implemented? My two thoughts were

Build list of all valid passwords and their corresponding states. Reject anything not on the list, and load the corresponding state when correct input is received.
Represent the state as a binary string, and make that the password. If the user's input parses validly, assume it to be valid and set it to the state.

What are the concerns with each of these approaches, and is there another way to go about this that I've overlooked?

Note: If this question is tagged poorly, it's because this is my first question on gamedev.stackexchange, and I'm not yet familiar with the ta


texts: I've been curious about game structure for some time now. Does everyone who is a game programmer come up with there own approach to structure there game, or is there like some sort of defined layout. to put this in prospective. Lets say a game programmer wanted to create a tiled map. Is there a specific way to do this, or does the every programmer do it there way.


texts: Creating own archive file format for levels? (.wad like)

texts:
I know there are similar questions but my question but my question is about taking some files (like png spritesheets, txt data) and put them in one archive file in general.

If I'm correct then I just have to read the files then open a new file with a custom format like ".mytar" than in a specific order write the binary data of the png and txts into it.

I have to specify a header and a "separator" to know where the next file starts.

I'm asking of something like the .wad file in Doom, they contained the sprites, level data all in one.

I didn't find any good tutorial or "guide" about how to design an uncompressed archive.

I know it would be simplier to store it in a "known" file format like .tar instead of creating my own but I want to learn and develop my skills, also I would love to feel that I create that file format :)

I don't know if I'm right...and I'm begging for some help :)

(Sorry if my Englis is a bit wrong... :) )


texts: How can i handle collision response in a voxel game?

texts: I'm making a voxel game with cubes - like in minecraft - and I have figured out how to check wether the player is colliding with a voxel, I have just done it by checking wether the player is within a voxel which is not air, however I don't know how to respond to that i know that the player is inside of a solid cube/voxel. Can anyone please suggest how to do it?


texts: Audio Plays A Second Time When Going Back To Menu Unity

texts:
I am trying to have my background music keep playing in between scenes, but the music just plays another copy of itself instead of destroying itself to let only one copy play at a time. This is my code :

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

public class MusicManager : MonoBehaviour {

    public static MusicManager instance;

    void Awake() {
        if (instance != null && instance != this) {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
    }
}

I'm not quite sure what I am doing right/wrong so any help is appreciated.

Edit: I found something that works

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

public class MusicManager : MonoBehaviour {

    private static MusicManager instance = null;
    private static MusicManager Instance {
        get {
            return instance;
        }
    }

    void Awake() {
        if (instance != null && instance != this) {
            Destroy(gameObject);
            return;
        } else {
            instance = this;
        }

        DontDestroyOnLoad(this.gameObject);
    }
}

This thread can be closed now.


texts: Jump function moves object horizontal after dash function

texts:
I have a dash function in my game as well as a jump function. Both of them works completely fine all by themselves. The jump works find and the dash works fine, however, I want to be able to jump cancel from my dash. During my dash, when I try to hit the jump button, the charater object moves horizontally instead of vertically. It almost acts as a second dash.

What I want to happen is the character to be able to jump vertically out of my characters dash. Can someone guide me in the right direction to my desired results?

if (keyboard_check(ord("D")) && !place_meeting(x + 2, y, obj_hitbox_wall)) {
    x += 2;
    image_xscale =+1;
    directionFacing = "Right";
}
if (keyboard_check(ord("A")) && !place_meeting(x - 2, y, obj_hitbox_wall)) {
    x -= 2;
    image_xscale =-1;
    directionFacing = "Left";
}
///// WALL HIT DETECTION START /////
if (!place_meeting(x,y+2,obj_hitbox_wall)){
    gravity = .25;
    grounded = false;
} else {
    vspeed = 0;
    gravity = 0;
    grounded = true;
    jumpDash = false;
}
///// WALL HIT DETECTION STOP /////

///// DOUBLE JUMP PROPERTIES START /////
if (grounded == false && jumped == true) {
    if (keyboard_check_pressed(vk_space)) {
        vspeed = 0;
        vspeed -= 5;
        jumped = false;
    }
}

if (grounded == true) {
    if (keyboard_check_pressed(vk_space)) {
        vspeed -=5;
        jumped = true;
    }
}
///// DOUBLE JUMP PROPERTIES END /////

///// DASH PROPERTIES START /////
if (dashed == false && keyboard_check_pressed(vk_shift) && jumpDash == false) {
    if (directionFacing = "Right") {
        vspeed = 0;
        gravity = 0;
        speed += 8;
        dashed = true;
    }

    if (directionFacing = "Left") {
        vspeed = 0;
        gravity = 0;
        if (grounded == true) {
            speed -= 8;
        } else {
            speed+=8;
        }
        dashed = true;
    }

}

if (dashed == true && directionFacing = "Right") {
     speed -= .4;
     direction = 0;
    if (speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0;
    }
}

if (dashed == true && directionFacing = "Left") {
    if (grounded == true){
        speed += .4;
        direction = 0;
    } else {
        speed -= .4;
        direction = 180;
    }
    if (grounded == true && speed >= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    } else if (grounded == false && speed <= 0) {
        dashed = false;
        gravity = .25;
        speed = 0
    }
}
///// DASH PROPERTIES END /////

///// JUMP DASH PROPERTIES START /////
if (grounded == false && dashed == true) {
    jumpDash = true;
}
///// JUMP DASH PROPERTIES END /////


texts: Upgrade to Unity 2018.2.2f1 resulting in missing file errors from Visual Studio

texts:
After being prompted by Unity to upgrade and doing so, Visual Studio is now giving me a long list of errors in the project about missing files.

Error   CS2001  Source file 'Packages\com.unity.textmeshpro\Scripts\Runtime\FastAction.cs' could not be found.  Unity.TextMeshPro   C:\Nightmare Games\Games\In Production\H0V3R\CSC    1   Active
Error   CS2001  Source file 'Packages\com.unity.textmeshpro\Scripts\Runtime\MaterialReferenceManager.cs' could not be found.    Unity.TextMeshPro   C:\Nightmare Games\Games\In Production\H0V3R\CSC    1   Active
Error   CS2001  Source file 'Packages\com.unity.textmeshpro\Scripts\Runtime\PackageResourceImporterWindow.cs' could not be found.   Unity.TextMeshPro   C:\Nightmare Games\Games\In Production\H0V3R\CSC    1   Active

There are 45 of these, and they're all in the project Unity.TextMeshPro.  I've looked for these files and they don't see to be anywhere on my PC.  Should I try reinstalling Unity or starting a new project again?  Has anyone else run into this?


texts:
I tried to search different solutions but also due to the lack of knowledge in camera handling I found none fitting my needs.

The situation is the following.

I have a 2d game structured in rectangular rooms and I want the camera to always have the whole room visible in the screen despite the screen resolution and the room bounds.

Any clue?

Edit:
Sorry for really bad painting, this is what I'd like to achieve somehow.

The camera viewport is where, inside the screen, the game will flow. everything else will be static, like a GUI frame with general informations and commands.


texts: Loading source controlled MonoDevelop project leaves out some folders

texts:
I have recently started using version control in MonoDevelop and have discovered that if I include a folder containing for example Scenes that they will be included when I push changes to master.

My structure is:

Scripts

--> Armour.cs

--> Inventory.cs

Scenes

--> Scene01.unity

However when I reopen the unity project and look at the code solution only the Script directory and the files within it appear and the Scenes folder is absent.

Strangely enough Scene01.unity is still getting picked up if I make a change and go to commit changes.

This is what I want my project to look like

Does anyone know why this is happens and if there is any way to resolve this?

NOTE: As a basic work around I can manually include the file when it disappears however when I have a large amount of assets this could become a painful task. Also if I load the project using MonoDevelop it loads fine, but opening from Unity itself seems to overwrite the solution files.


texts: Why am I getting the error "SDL_Event has not been declared"?

texts:
I don't understand what I'm doing wrong. In my game.cpp, I have this:

void Game::input() {
    SDL_Event e;
    while(SDL_PollEvent(&e)) {
        if(e.type == SDL_QUIT) {running=false; cout << "Quitting" << endl;}
        if(e.type == SDL_KEYDOWN) {
            if(e.key.keysym.sym == SDLK_ESCAPE) {
            running=false;
            }
            moveSprite(e);
        }
        if(e.type == SDL_KEYUP) {
        }
        SDL_GetMouseState(&mousex, &mousey);
    }
}

In my player header file, I have:

class player {
public:
    player();
    int getPlayerX();  //get player's x position
    int getPlayerY();  //get player's y position
    void moveSprite( SDL_Event& e );
private:
    int xPos, yPos;
};

I'm getting the following error:

  SDL_Event has not been declared"

on the line: void moveSprite( SDL_Event& e );

It seems like something simple but I've been staring at it for hours and I can't figure it out. Be gentle, I'm a third semester programming student.


texts: (unity 2D) How to design valid playable levels?

texts:
I'm prototyping a 2D platofrm game with simple jump to tap mechanics. Here, the ball is constantly moving forward with a fixed velocity, and jumps when a key is pressed. For reference, image below :

This is one of the many scenarios in the game. Difficulty I have is determining the position of various obstacles. For example, in the attached image, how to determine how far the two obstacle pairs should be so that it's just right. Make sure player can jump through the first pair and clear the second pair without making it too easy or nearly impossible to clear.
Any level design validation techniques?


texts: Does gluLookAt add or set the view matrix variables?

texts:
I'm trying to rotate the camera view in PyOpenGL, but it's not working well. The weirdest behavior I've noticed is that putting gluLookAt in a loop seems to change the camera view, even when I'm not changing the inputs as the loop continues.

So while I'd expect something like:

gluLookAt(0,0,0, 0,0,-5, 0,0,1)

to keep the camera constantly pointing downwards, it seems to rotate the view in some strange way, with the objects being rendered leaving the maximum clipping radius after a while.

My question is, does gluLookAt take into account the previous camera settings, or do I need to look for something else wrong in my code?


texts: How can I pass an array of matrices to a VertexShader

texts:
I'm trying to learn how to use OpenGL but I'm having problems trying to pass an array of matrices to my VertexShader. I think the problem is in the VertexShader because it seems the values in modelvalue are passed correctly to the components of model, but for some reason at the end only one of the three cubes I've created is drawn. Here's the Main code.

glm::mat4 model[3];
GLint ModelLocation = glGetUniformLocation(MyShader.program, "model");
vector<GLfloat> modelvalue;
const int n = int(sizeof(model[0]) / sizeof(GLfloat));

for (int i = 0; i < 3; i++) {
    model[i] = glm::translate(model[i], cubePositions[i]);

    for (int j = 0; j < n; j++) {
        modelvalue.push_back(glm::value_ptr(model[i])[j]);
    }

}
glUniformMatrix4fv(ModelLocation, 3, GL_FALSE, &modelvalue[0]);

The VertexShader:

   #version 400 core
  layout (location = 0) in vec3 Position;
  layout (location = 1) in vec2 texCoord;
  out vec2 TexCoord;
  out vec4 position0;
  out vec4 position1;
   out vec4 position2;
  uniform mat4 model[3];
  uniform mat4 view;
  uniform mat4 projection;
  void main()
  {
  position0 = projection * view * model[0] * vec4(Position,1.0f);
  position1 = projection * view * model[1] * vec4(Position,1.0f);
  position2 = projection * view * model[2] * vec4(Position,1.0f);
  TexCoord = vec2(texCoord.x,1-texCoord.y);
   }

And the FragmentShader:

  #version 400 core

  layout (location = 0) in vec3 Position;
  layout (location = 1) in vec2 texCoord;

  out vec2 TexCoord;
  out vec4 position0;
  out vec4 position1;
  out vec4 position2;
  uniform mat4 model[3];
  uniform mat4 view;
  uniform mat4 projection;
  void main()
  {
  position0 = projection * view * model[0] * vec4(Position,1.0f);
  position1 = projection * view * model[1] * vec4(Position,1.0f);
  position2 = projection * view * model[2] * vec4(Position,1.0f);
  TexCoord = vec2(texCoord.x,1-texCoord.y);


texts:
I am trying to draw a picket fence, but the center of the picket vertex looks bent in the middle,

why is the picket bending inwards to the left?

// draw fence pickets
float a;
for (a=-25; a<=25; a+=0.256) {

    glBegin(GL_POLYGON);
    glColor3f(  1,  1,  1 );
    glVertex3f( a,       25, 0 );
    glVertex3f( a+0.128, 25, 0 );
    glVertex3f( a,       25, 1 );
    glVertex3f( a+0.128, 25, 1 );
    glEnd();

}


texts: How to move a b2Body explosively to a new Location

texts:
I am building an Game based on Box2d with the following basic structure:

The Box2d World itself does not have any Gravity and is filled with some bodies (sheres and simple polygons) of more or less the same size. The user can select on of them and if he clicks on the free space, the selected body should be moved onto the "point of click".

The movement should be explosive, what the use of b2Body.ApplyImpulse suggests, but also stop quickly when the point is reached.

This leads me to two problems:

Which method should i use: ApplyImpulse or ApplyForce? How could I calculate the right vector of the impulse, if you would use this method?

How could I correct the body's way if it collides with another?

Greetings Philipp


texts: Techniques to prevent non-official clients in network gaming?

texts:
In multi-player network games, what techniques exist to try to ensure that users are connecting with the official client application, and not some hacked client app?

I realise there is probably no sure-fire way to do this, but rather I'm interested in techniques that can be employed to mitigate the problem.

I'm especially interested in any techniques that can be used for web based games, but I imagine most can be applied generally.

Thank you!


texts: Is it possible to use one if statement for each level scene?

texts:
I'm working on a platform game where you as a player have to collect logs, to keep on all the fires in the level. Each campfire has a timer, which ensures that every x number of seconds the animation of the fire is changed to a numb fire. The timer of a campfire is blocked by the script, when the player has received the fire at 100%. When all fires are 100% you won, if not you lose.

Know I use the following if statement to check if the player has won or lose:

if (Application.loadedLevelName == "Level 0") {

        if (campfireAmount == allCampfireFull) {
            // Do something
            print ("level 1 complete");
            Application.LoadLevel (6);
        }

        if (campfireAmount == allCampfireEmpty) {
            // Do something
            print ("level 1 failed");
            //Application.LoadLevel ("GameOver");
        }

    }

What I searching for is how I can make this if statement useful for each level, whiteout use for each level scene above if statement. Beside that, what I want is that after each level you get a win scene (if possible a reusable scene) and after clicking in that scene on a button, you should go to the next level scene. Is there a way to load the next level, whiteout set a hard number of the rang list of "Build Settings"?


texts:
Im trying to find the "best way" to apply a texture to a heightmap with opengl 3.x.

Its really hard to find something on google because tutorials are olds and they're all using different methods, im really lost and i dont know what to use at all.

Here is my code that generates the heightmap (its basic)

    float[] vertexes = null;
    float[] textureCoords = null;

    for(int x = 0; x < this.m_size.width; x++)
    {
        for(int y = 0; y < this.m_size.height; y++)
        {
            vertexes ~= [x, 1.0f, y];
            textureCoords ~= [cast(float)x / 50, cast(float)y / 50];
        }
    }

As you can see, i dont know how to apply the texture at all (i was using / 50 for my tests).

Result of that code :

I would like to have something very basic like :

(you can find more pics in his blog)

Edit : my texture size is 1024x1024.


texts: Cocos2d: Adding a CCSequence to a CCArray

texts:
I have a problem with an action performed by a sprite. I have one CCSequence in a CCArray and I have an scheduled method (is called every 5 seconds) that make the sprite run the action. The action is performed correctly only the first time (the first 5 seconds), after that, it does not.

Here is the code:

In .h ->

@interface PowerUpLayer : CCLayer {
    PowerUp *powerUp;
    CCArray *trajectories;
}

@property (nonatomic, retain) CCArray *trajectories;

In .mm ->

@implementation PowerUpLayer

@synthesize trajectories;

-(id)init
{
    if((self = [super init]))
    {
        [self createTrajectories];
        self.isTouchEnabled = YES;
        [self schedule:@selector(spawn:) interval:5];
    }

    return self;
}

-(void)createTrajectories
{
    self.trajectories = [CCArray arrayWithCapacity:1];

    //Wave trajectory
    ccBezierConfig firstWave, secondWave;

    firstWave.controlPoint_1 = CGPointMake([[CCDirector sharedDirector] winSize].width + 30, [[CCDirector sharedDirector] winSize].height / 2);//powerUp.sprite.position.x, powerUp.sprite.position.y);
    firstWave.controlPoint_2 = CGPointMake([[CCDirector sharedDirector] winSize].width - ([[CCDirector sharedDirector] winSize].width / 4), 0);
    firstWave.endPosition = CGPointMake([[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height / 2);

    secondWave.controlPoint_1 = CGPointMake([[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height / 2);
    secondWave.controlPoint_2 = CGPointMake([[CCDirector sharedDirector] winSize].width / 4, [[CCDirector sharedDirector] winSize].height);

    secondWave.endPosition = CGPointMake(-30, [[CCDirector sharedDirector] winSize].height / 2);

    id bezierWave1 = [CCBezierTo actionWithDuration:1 bezier:firstWave];
    id bezierWave2 = [CCBezierTo actionWithDuration:1 bezier:secondWave];

    id waveTrajectory = [CCSequence actions:bezierWave1, bezierWave2, [CCCallFuncN actionWithTarget:self selector:@selector(setInvisible:)], nil];

    [self.trajectories addObject:waveTrajectory];
    //[powerUp.sprite runAction:bezierForward];

    //        [CCMoveBy actionWithDuration:3 position:CGPointMake(-[[CCDirector sharedDirector] winSize].width - powerUp.sprite.contentSize.width, 0)]
    //[powerUp.sprite runAction:[CCSequence actions:bezierWave1, bezierWave2, [CCCallFuncN actionWithTarget:self selector:@selector(setInvisible:)], nil]];

}

-(void)setInvisible:(id)sender
{
    if(powerUp != nil)
    {
        [self removeChild:sender cleanup:YES];
        powerUp = nil;
    }
}

This is the scheduled method:

-(void)spawn:(ccTime)dt
{
    if(powerUp == nil)
    {
        powerUp = [[PowerUp alloc] initWithType:0];

        powerUp.sprite.position = CGPointMake([[CCDirector sharedDirector] winSize].width + powerUp.sprite.contentSize.width, [[CCDirector sharedDirector] winSize].height / 2);

        [self addChild:powerUp.sprite z:-1];

        [powerUp.sprite runAction:((CCSequence *)[self.trajectories objectAtIndex:0])];
    }
}

I don't know what is happening; I never modify the content of the CCSequence after the first time.


texts: Does SDL running on Mac OS not recognize Xbox controllers?

texts:
I'm trying to learn a bit of SDL, and have been bouncing between Windows and Mac platforms, but am noticing that an SDL program running on my Macbook doesn't recognize the presence of the Xbox controller I have plugged in. I haven't been able to find anything concrete that says one won't work with the other, which is why I'm here.

For reference, here's the code that I'm using to check for the existence of a joystick via SDL:

bool hasJoystick = false;
hasJoystick = (SDL_NumJoysticks() >= 1) ? true : false;
if(hasJoystick) {
    for(int i = 0; i < SDL_NumJoysticks(); i++)
        std::cout << "Joystick " << i+1 << "   " << SDL_JoystickName(i) << std::endl;
} else {
    std::cout << "Yo. No joystick here, kid." << std::endl;
}

I consistently see the "Yo. No joystick here, kid." message in my console. I'm using SDL 1.2 with, and have copied the framework folder to all the appropriate locations. Also, the controller I'm using is 3rd party, but I'm not sure whether that's relevant.


texts: Resolution independence (for touch input on different mobile screens)

texts:
I have drag mechanic in Unity game and I want to have same experience in all devices. I've done this before in another game engine and now that Unity gives us Dpi with Screen.DPI, it should be much easier to achieve, but I can't figure it out for the love of the god.

My theory is you have to divide the delta movement of touch with Screen.Dpi to normalize the movement and make it same across devices with different screen sizes and dpi's:

(touch0.deltaPosition.x / dpi) * SENSITIVITY * Time.deltaTime;

But this doesn't work. Would someone please tell me why?

I've done extensive search on this but surprisingly nothing much can be found.

Thanks in advance and regards.


texts:
I recently added framebuffer rendering to my game and rendering to the FBO works (verified with glGetTexImage), but when I go to render a quad to show the result nothing is drawn to the screen. I'm using OpenGL 3.3 Core, so I'm drawing using vertex buffers for the quad and I have two simple pass-through shaders to display the quad. I apologize for the amount of code that follows, but I felt it was all necessary for anyone who ends up looking at this.

Quad generation:

// create vertices
// Vertex(position, normal, tex coord)
quadVertices.Add( Vertex( Vector3( -1.0f,  1.0f, 0.0f ), Vector3(), Vector2( 0.0f, 1.0f ) ) );
quadVertices.Add( Vertex( Vector3( -1.0f, -1.0f, 0.0f ), Vector3(), Vector2( 0.0f, 0.0f ) ) );
quadVertices.Add( Vertex( Vector3(  1.0f, -1.0f, 0.0f ), Vector3(), Vector2( 1.0f, 0.0f ) ) );
quadVertices.Add( Vertex( Vector3(  1.0f,  1.0f, 0.0f ), Vector3(), Vector2( 1.0f, 1.0f ) ) );
quadVertices.SendData(); // gl*Buffer* methods wrapper

// create indices (quadIndices is a buffer of 16-bit integers)
quadIndices.Add( 0 );
quadIndices.Add( 1 );
quadIndices.Add( 2 );
quadIndices.Add( 0 );
quadIndices.Add( 2 );
quadIndices.Add( 3 );
quadIndices.SendData();

Quad rendering:

glDisable( GL_DEPTH_TEST );
glDisable( GL_CULL_FACE );

// bind the texture
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, framebuffer.GetColorHandle() );
_shader.Seti( "texture0", 0 );

 // projection matrix is glm::ortho( -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f );
_shader.Set( "proj", _projection );

// get attributes
int vertex   = _shader.GetAttribLoc( "vertex" );
int texCoord = _shader.GetAttribLoc( "texCoordV" );

// bind buffers
quadVertices.Bind();
quadIndices.Bind();

// enable arrays and point to data
glEnableVertexAttribArray( vertex );
glVertexAttribPointer    ( vertex,   3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (void*)( 0 ) );
glEnableVertexAttribArray( texCoord );
glVertexAttribPointer    ( texCoord, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (void*)( sizeof( Vector3 ) * 2 ) );

// draw!
glDrawElements( GL_TRIANGLES, quadIndices.Size(), GL_UNSIGNED_SHORT, 0 );

// disable arrays
glDisableVertexAttribArray( vertex   );
glDisableVertexAttribArray( texCoord );

// unbind everything
quadVertices.Unbind();
quadIndices.Unbind();
glBindTexture( GL_TEXTURE_2D, 0 );

glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );

Vertex shader:

#version 330 core

in  vec3 vertex;
in  vec2 texCoordV;
out vec2 texCoordF;

uniform mat4 proj;

void main()
{
    texCoordF = texCoordV;
    gl_Position = proj * vec4( vertex, 1.0 );
}

Fragment shader:

#version 330 core

layout(location=0) out vec4 fragColor;

in vec2 texCoordF;

uniform sampler2D texture0;

void main()
{
    fragColor = texture( texture0, texCoordF );
}


texts: Raycast doesn't point on the right direction

texts:
The raycast line im rendering is acting weird, it doesn't point where I want it to.

I want it to point from the yellow object to the selected one but it draws it at another position.

Here is my script:

    #pragma strict

var player : Transform;
var turret : Transform;

var bullet : Transform;
var barrelEnd : Transform;

var shootRate = 0.3;

var canShoot : boolean = true;

var soundEffect : AudioClip;

function Update()
{
    shoot();
}

function shoot()
{
    turret.LookAt(player);
    var hit : RaycastHit;
    var fwd = turret.forward;
    if(Physics.Raycast(turret.position, player.position,hit, Mathf.Infinity))
    {
        if(hit.collider.transform.gameObject.tag == "Player")
        {
            if(canShoot == true)
            {
                var bulletInstance : Transform;
                bulletInstance = Instantiate(bullet, barrelEnd.position, transform.rotation);
                bulletInstance.LookAt(player.position);
                audio.PlayOneShot(soundEffect);
                w();
            }
        }
    }

    Debug.DrawRay(player.position, transform.position);
}

function w()
{
    canShoot=false;
    yield WaitForSeconds(shootRate);
    canShoot=true;
}

Thank you! I hope someone can help


texts: Where should multiplayer games start? Client or server?

texts:
I'm starting to make a small multiplayer game, and even though I have experience with games and networking, there's just one thing that keep me from making this.

The question is: When starting a multiplayer game, should one start making the server first, or the client first?

This looks like a dead-lock for me, because while starting on the client, seems to be the a good option (you'll make a game, which you are already very good at doing probably, and you'll have something to look for progress), you will fall on the trap that probably most of the code effort you put into making that game will have to be thrown away and remade on the server side.

And starting on the server-side is just the opposite: You'll have nothing to look upon, so you can't know if you're making progress. And if that wasn't bad enough, you'll also have to throw lots of stuff away, since you have no game to check if that will have to indeed work like that.

Is there a correct answer for this?


texts: how to move character move on a circular surface in only one direction?

texts:
Making a 2d game:

I want to move character on circular surface only in one direction?

Script attached to child object is:

    public GameObject ball;
    float speed=2f;

    // Start is called before the first frame update
    void Start()
    {
        GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        Left();
    }

    void Left()
    {
        if(Input.GetKey(KeyCode.LeftArrow))
        {
            ball.GetComponent<Rigidbody2D>().AddForce(Vector3.forward * speed);
            //transform.Rotate(Vector2.left);
        }
    }

Note:
character will move on a circular surface in only one direction...

Image reference:


texts: Bounding Box Collision Glitching Problem (Pygame)

texts:
So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better).

Here's the whole code:

from pygame import *

DONE = False
screen = display.set_mode((1024,768))
class Thing():
    def __init__(self,x,y,w,h,s,c):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.s = s
        self.sur = Surface((64,48))
        draw.rect(self.sur,c,(self.x,self.y,w,h),1)
        self.sur.fill(c)
    def draw(self):
        screen.blit(self.sur,(self.x,self.y))
    def move(self,x):
        if key.get_pressed()[K_w] or key.get_pressed()[K_UP]:
            if x == 1:
                self.y -= self.s
            else:
                self.y += self.s
        if key.get_pressed()[K_s] or key.get_pressed()[K_DOWN]:
            if x == 1:
                self.y += self.s
            else:
                self.y -= self.s
        if key.get_pressed()[K_a] or key.get_pressed()[K_LEFT]:
            if x == 1:
                self.x -= self.s
            else:
                self.x += self.s
        if key.get_pressed()[K_d] or key.get_pressed()[K_RIGHT]:
            if x == 1:
                self.x += self.s
            else:
                self.x -= self.s
    def warp(self):
        if self.y < -48:
             self.y = 768
        if self.y > 768 + 48:
             self.y = 0
        if self.x < -64:
             self.x = 1024 + 64
        if self.x > 1024 + 64:
             self.x = -64
r1 = Thing(0,0,64,48,1,(0,255,0))
r2 = Thing(6*64,6*48,64,48,1,(255,0,0))
while not DONE:
    screen.fill((0,0,0))
    r2.draw()
    r1.draw()
    # If not intersecting, then moves, else, it moves in the opposite direction.
    if not ((((r1.x + r1.w) > (r2.x - r1.s)) and (r1.x < ((r2.x + r2.w) + r1.s))) and (((r1.y + r1.h) > (r2.y - r1.s)) and (r1.y < ((r2.y + r2.h) + r1.s)))):
        r1.move(1)
    else:
        r1.move(0)
    r1.warp()
    if key.get_pressed()[K_ESCAPE]:
        DONE = True
    for ev in event.get():
        if ev.type == QUIT:
            DONE = True
    display.update()
quit()

The problem:

In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast.

In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them.

The code-problem illustrated:

When the player goes towards the wall (Fine).

When the player goes towards the wall and press the opposite direction. (It glitches through).

Here is the logic I've designed before implementing it:

I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching-possibilities. What do you suggest?


texts: Determine "bounding box size" (not scale) of model in MonoGame

texts:
I'm working on integrating some the 3D models I import into my physics system by trying to take their "size" and use that as the side for objects within my physics system. When I say size, I'm referring essentially to a bounding box size around my model. Here's an example of a test level layout I'm designing:

All of the cubes below are 1x1 units in Blender (measuring from the center), so I've been able to just code in those assumptions. However, it starts to get more interesting when you consider the slope and smaller platform I have.

For the slopes, I've found an easy hack for the time being (as long as their size remains 1x1). However, the platforms are throwing me off. A few things to call out with the platform model:

The model itself is centered at (0,0,0) and no scaling was done on the model itself in Object Mode
I scaled down the Z of the model in Edit Mode, while the model itself remains at (1,1,1) scaling

I'm now trying to figure out how to get some form of size for the model. For what I'm looking for, if we assume the cubes I have are bounds box size of (1,1,1), then this platform would be a bounding box size of (1, 1, .25). I would assume that I would need to look at the model's meshes to determine this, but I'm not entirely sure

Any help on this would be appreciated. Thanks!


texts: rotating a sprite around a non-fixed center

texts:
I'm trying to get this character to spin in a circle to aim at the cursor. It all works pretty well, but I can't get the image to rotate around its center. Only around its corner. I've been trying to find a solution be using some crazy trig stuff, but I'm not getting anywhere.

public void draw(Graphics g, double inter)
{
BufferedImage im;
Graphics2D g2d = (Graphics2D)g;
GImage gImage;

gImage = GImages.getImage(p.sprite);
im = gImage.imageFile;
AffineTransform at = new AffineTransform();
at.translate((p.xcord+((float)p.width/2))+(p.xspd*inter), (p.ycord+((float)p.height/2))+(p.yspd*inter));
at.rotate(p.angle+(Math.PI/2));
at.scale((double)gImage.xsize/im.getWidth(), (double)gImage.ysize/im.getHeight());
//at.translate(-(float)p.width/2, -(float)p.height/2);
g2d.drawImage(im, at, null);
g2d.setColor(Color.BLUE);
g2d.drawRect((int)p.xcord,(int)p.ycord,1,1);
//g.setColor(Color.BLACK);
//g.drawString(p.suh, (int)(p.xcord+(p.xspd*inter)), (int)(p.ycord+(p.yspd*inter)));
}

p is my sprite object, the cords make up the point of the corner of the image.
The sprite moves around the screen, so I can't use a fixed point method as far as I know.
If anyone has any suggestions to make this work.


texts: How should VertexBuffers be used with Multiple Monitors in DirectX 9

texts:
I am currently using DirectX 9 on a machine with two GPUs and three monitors. I am currently trying to draw a triangle on each monitor using vertexbuffers; A directx helloworld with multiple monitors if you will. I am familiar with some DirectX coding, but new to multiple monitor DirectX coding. I may be going about this the wrong way, so please do correct me if I'm doing something wrong. I have created a Direct3D Device for each enumerated adapter sharing the same Form handle. This allows me to successfully use all three monitors in full-screen mode.

For Each Adapter In Direct3D.Adapters
    Dim PresentParameters As New PresentParameters
    'Setup PresentParameters
    PresentParameters.Windowed = False
    PresentParameters.DeviceWindowHandle = MainForm.Handle

    Dim Device as New Device(Direct3D, Adapter.Adapter, DeviceType.Hardware, PresentParameters.DeviceWindowHandle, CreateFlags.HardwareVertexProcessing, PresentParameters)

    Device.SetRenderState(RenderState.Lighting, False)
    Devices.Add(Device)
Next

I can also draw text to each device successfully using a different Font for each Device.

When I render a triangle using a different VertexBuffer for each Device, only two monitors display the triangle. One of the two monitors on the same GPU, and the monitor on it's own GPU display properly.

VertexBuffer = New VertexBuffer(Device, 4 * Marshal.SizeOf(GetType(ColoredVertex)), Usage.WriteOnly, VertexFormat.None, Pool.Managed)

Dim Verts = VertexBuffer.Lock(0, 0, LockFlags.None)
Verts.WriteRange({
    New ColoredVertex(-.5, -.5, 1, ForeColor),
    New ColoredVertex(0, .5, 1, ForeColor),
    New ColoredVertex(.5, -.5, 1, ForeColor)
})

VertexBuffer.Unlock()

VertexDeclaration = New VertexDeclaration(Device, {
    New VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
    New VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
    VertexElement.VertexDeclarationEnd
})

Render Code:

Device.SetStreamSource(0, VertexBuffer, 0, Marshal.SizeOf(GetType(ColoredVertex)))
Device.VertexDeclaration = VertexDeclaration
Device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1)

I have to assume the fact that they share the same physical card comes into play. Should I use multiple buffers on the same card, and if so, how? Or what is the way I should access the VertexBuffer across Devices?

Another thought I had was the non working monitor acts like there are no lights. Is turning off lighting on each device on the same card causing issues somehow?