texts:
I'm currently working on a project which uses Box2D, when the player uses a certain key it should anchor to the ground. For that I use a weld joint, but when I add the joint the game will sometimes crash, it has a 1/10 change to crash.

The error I recieve:

Showing the controller
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at org.jbox2d.dynamics.Island.add(Island.java:577)
at org.jbox2d.dynamics.World.solve(World.java:1073)
at org.jbox2d.dynamics.World.step(World.java:598)

The code for adding the joints:

WeldJointDef def = new WeldJointDef();
def.initialize(body, anchoredObject.body, body.getWorldCenter());
weldJoint = (WeldJoint) world.createJoint(def);

I still get the error if I synchronize it


texts:
I have two perpendicular planes in xz and yz like this

I want to find the projection of the vertices of plane 2 on plane 1 using raycasting.The rays are hitting the plane but the log is showing zeros. why?

using UnityEngine;
using System.Collections.Generic;

//[ExecuteInEditMode()]
public class PlaneManipulation : MonoBehaviour {
    Ray ray;
    RaycastHit hit;

    Mesh mesh;
    private Vector3[] vertices;
    public float rayLength;

    public LayerMask planeLayer;

    void ChangeMesh() {
        mesh = GetComponent<MeshFilter>().sharedMesh;
        vertices = mesh.vertices;
        //using only the first row of the vertices from the plane
        for (int i = 0; i < 11; i++)
        {
            Vector3 vert = transform.TransformPoint(vertices[i]);

            Physics.Linecast(vert, Vector3.up, out hit,planeLayer);

            Debug.DrawRay(vert, Vector3.up);

            Debug.Log("hitPoint = " + hit.point);

            //vert.y = hit.point.y;
            //vertices[i].y = hit.point.y;
            //vertices[i] = transform.InverseTransformPoint(vert);
        }

        mesh.vertices = vertices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
    }

    void Update() {

        ChangeMesh();
    }
}


texts:
I can check if coroutine still running by setting boolean variable outside the coroutine and then letting the coroutine itself set the value to true when it runs and set it to false when it decide to stop .
But this method of detecting whether coroutine still active or not doesn't work when the coroutine crashed due to error (invalid input, null reference , ect) because the boolean variable remain true while the coroutine itself has stopped due to error.
How do i check if coroutine still running or not in current frame ? i can't spend my code checking for next frame .
Preferably C# , but answer in javascript also accepted.


texts: Algorithm that always returns the same pseudorandom output if given the same input of seed, x and y?

texts:
I've been trying to find an algorithm that will take in an x value, a y value, and a seed value and then spit out a number between 0 and 255 (or an int that I can cut up into bytes). I want to be able to feed in the tile a player is standing on during some ingame event and get the same value for the same tile any time the player is in that level. I don't want to use a linear PRNG because I just want to check a few tiles at any one time, not go though several of them to get a sequence.

I tried modifying an Xor Shift PRNG, but I just end up making patterns like below:

ubyte Xor( int wx, int wy, ulong seed ){
    int result = wx ^ (wx >> 7) ^ wy ^ (wy >> 9) ^ seed ^ (seed << 6);
    return cast(ubyte)result;
}

My input values are likely to be 0-32000 for x and y, and seed can be any ulong value. I'd like to avoid floating point math as it's not deterministic between machines (so it would screw up some multiplayer stuff). I just need to not get a repeating pattern, and have each seed produce a distinctly different output. Can anyone point me in the right direction?


texts: How do we apply different textures to different faces generated via geometry shader?

texts:
I am trying to render a cube by starting of with one vertex into the shader, then geometry shader to expand into a cube, and then apply a different texture to each side. The part I am facing the issue with applying unique textures to each side.

So I am currently doing this by creating it via quads pushing the vertices, and applying the textures one by one. In fact, I drawIndexed() a set of vertices, then switch over to a different textures every 6 vertices. But pushing in so many vertices is expensive for higher FPS. So, I looked in to Geometry shader and it seems like it did the job. After studying it, I understand how to develop the vertices in the geometry shader. However, I don't know how to apply a different texture say every 6 vertices - since we are in the pipeline already.


texts: Text tool for designing gameplay elements

texts:
I'm still in the design phase of my game and I'm realizing that there are too many elements to keep track of and it just looks like a mess in the plain text that I created it in. My notes are basically going to translate to the classes and subclasses that'll make up the objects within my game, but I'd like to find a tool that will make it simpler to keep track of. Here's an example of the structure of my notes:

NPCs:
    - Humans:
        - Human A: description
            - Abilities:
                - Ability A: description
                [...]
            - Attributes:
                - Attribute A: description
                [...]
        - Human B: description
            - Abilities:
                - Ability A: description
                [...]
            - Attributes:
                - Attribute A: description
                [...]
    - Elves:
        - Elf A: description
            - Abilities:
                - Ability A: description
                [...]
            - Attributes:
                - Attribute A: description
                [...]
        - Elf B: description
            - Abilities:
                - Ability A: description
                [...]
            - Attributes:
                - Attribute A: description
                [...]
    [...]
World:
    - Continent A: overall description
        - City A: city description
            - Building A: description
            [...]
        [...]
    [...]
Items:
    - Melee: overall description
        - Melee Weapon A: description
            - Damage: X
            - Damage Type: some type
            [...]
        [...]
    - Ranged: overall description
        - Ranged Weapon A: description
            - Damage: X
            - Damage Type: some type
            [...]
        [...]

And so on...

Even this simple list is starting to look messy, and once you have pages of classes and multiple subclasses for each class along with lengthy descriptions, it gets really jarring when you view it.

What I would really like is a way to expand and collapse these elements so I can either view the big picture or go down to details, and maybe be able to set some groups a different color or make them bold, etc. for better viewing and categorization. It's basically a class diagram but with more game-world-related descriptions rather than function/method descriptions. I'm currently using Sublime for this, so either a plugin or a different tool that accomplishes this would really help. Thanks!


texts: Android AndEngine creating a body behind the sprite exactly

texts:
I am using AndEngine for Android. I created a body, but it is not behind the sprite as I wanted.

                                Body.setTransform(Sprite.getX()/32, Sprite.getY()/32, 0);

This is what I am currently using and this is how it appears.

My body is the white circular borders, and my sprite is the red circle.

and When I remove /32 from the code the body doesn't even appear.

Extra code;

                    FIXTURE_DEF = PhysicsFactory.createFixtureDef(
                            1,     // density
                            0.75f,  // elasticity
                            0.5f, // friction
                            false); // isSensor

the Body

                Body = PhysicsFactory.createCircleBody(this.physicsWorld, Sprite, BodyType.KinematicBody, this.FIXTURE_DEF);
                Body.setUserData("eSprite");
                this.physicsWorld.registerPhysicsConnector(new PhysicsConnector(Sprite, Body, true, true)

my sprite is 65px ..


texts: Sampled texture from bitmap font produces blue glow

texts:
I'm creating a texture is DirectX 11 from bitmap fonts. I realize that I can use DXTK, but this is an exercise for me, not in learning another library. My sample code looks like this.

// Object Declarations
Texture2D g_MeshTexture;            // Color texture for mesh

SamplerState MeshTextureSampler
{
    Filter = MIN_MAG_MIP_LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    return g_MeshTexture.Sample(MeshTextureSampler, input.uv);
}

The texture of the rendered font produces strange blue artifacts where the text should have alpha values but instead appear as blue.

I did try gamma color correction with the code

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    float4 sRGBA = g_MeshTexture.Sample(MeshTextureSampler, input.uv);
    float3 sRGB = float3(sRGBA.x, sRGBA.y, sRGBA.z);
    float3 gRGB = pow(sRGB, 1/2.2);

    return float4(gRGB.x, gRGB.y, gRGB.z, sRGBA.w);
}

However this did not provide results any different from what the image showed above. I sample the text from the bitmap data and store it in a vector when then is used to create the texture with CreateTexture2D.

for (long y = 0; y < m_texture_height; y++)
{
    for (long x = 0; x < m_texture_width; x++)
    {
        BYTE alpha = (bitmap_bits[m_texture_width * y + x] & 0xff);

        if (alpha > 0)
            pixel_data.push_back(0xFFFFFF00 + alpha);
        else
            pixel_data.push_back(0);
    }
}

My back buffer uses DXGI_FORMAT_R32G32B32A32_FLOAT, however I have tried DXGI_FORMAT_R8G8B8A8_UNORM and experienced no change. If there's any other information I should provide please let me know.


texts: Determining whether a large building should be split into multiple scenes

texts:
This is about designing a first person retro game in Unity3d. In this game the player would walk around inside a large maze-like building that has corridors on 10-15 different floors.

Each floor has a corridor that is set up as a square that surrounds all other corridors (which are set more or less randomly, like a maze) on that particular floor. The length of each side of this surrounding corridor is about 100 steps.

So, considering that this building would have about 10-15 floors constructed like this, the question I wanted to ask is whether it can be included as a single scene?

Or does the answer to this depend also on other factors such as the type of game assets and target devices?


texts: How should you structure your graphics system around your logic system?

texts:
C++ & Cocos2d-x, but I think the issue is language-independent.

I just recently finished up writing the foundational logic for my game. The way I've decided to keep my logic and my graphics decoupled is by simply having two base objects: LogicBody and GraphicsBody. Any object that needs to show up in the game needs to be comprised of both. So far, so good.

However, I am struggling with the initialization and interaction framework. I'll explain:

1) How should I make sure the logic body and graphics body stay together (in hopes of maintaining code readability).

Should they? Take the case of object Monster. It will need a logic body and a graphics body. But should both of these be contained in one overarching Monster class? Won't accessing either internal structure become unnecessarily verbose (i.e. Monster->getGraphicsBody() every time). However, this makes initialization easy:

Monster::init();

Alternatively, it is possible to initialize both logic and graphics separately:

Logic::init(); Graphics::init();

How can I then keep them abreast/aware of each other though? This will create clutter too, as I will likely need to call setters on each at initialization to make sure they reference each other:

Logic::setGraphicPtr(); Graphics::setLogicPtr();

2) What is the appropriate way to change graphics: polling, logic-driven, or both?

In the simplest of cases, updating graphics is as easy as polling direction, isMoving, health, etc. However, let's say that I want to play a particular animation when the Monster gets hit. The easiest way seems to be to call the "getHitAnimation" of the graphics body from within the logic body at the time of being hit. The alternative is to poll, but it seems that a certain point you will be polling twenty different variables, which has the potential to make the graphics implementation indecipherable without reference to the logic class anyways.

3) Should a logic body have reference to its graphics body at all?

I understand how clean it would be to simply have the graphics body reference the logic body for rendering purposes, in which case the logic body has no business with the graphics body. But what about the case where logic body A has met logic body B, and graphics bodies A and B need to interact. How do I let graphics bodies A and B know where to look for another?

I want to know the best way to implement these parallel systems with the least amount of coupling. Pseudo code welcomed.


texts: Why do transformation matrices always have an extra dimension?

texts: In 3D math I always see matrices with one additional dimension. For example, in 3D graphics, matrices are always 4x4 and in 2d they are 3x3 matrices. Can anyone explain why?


texts:
I've been working on a game for couple years now, its fairly original, has definite potential within an indie market, and appeal for the masses also.

I want to deploy on Android and PC, green-light it on steam and looking into Kickstarter. I'm also going to set up a website where it can be played, have a dedicated server to link 'matches' and post demos on sites like mofunzone and armorgames.

I've used Jbox2d, and am also curious about the licencing with this engine and can't seem to find documentation on that.

I'm almost done the 'demo' and my question is, how should I market it?

I was thinking I'd make the game free on android, charge something like $10 on steam, and charge say 1$ month to play online (for the pc version)

If anyone has any good links, research or advice from personal experience, it would be greatly appreciated.


texts: I'm just wondering why we need to call glDisableClientState(GL_VERTEX_ARRAY) after the drawing of a vertex array. Is it possible to just leave it there for the next drawing? Is there any side effect of doing this?


texts: How should I connect objects when using the MVC paradigm?

texts:
This has been confusing me for the past week as I am trying to make my first actual game. It's only my 2nd year learning Java so I am really trying to learn how to program like a professional organization and how classes interact and whatnot.

I found that the MVC is generally the pattern for professional programs (although there are different ways). I've been trying to code in this pattern and have been confounded by the connections. I don't understand code-wise how to connect them but I understand the concept.

For example, in my game I have a Card class which contains all the logic for the card but I also have a CardDisplay class which contains the paint override and extends JComponent displaying the image of the card and the listeners. Should I consolidate them together or are they suppose to be separate?

Also how do I connect the view to the controller such as my View class containing the JFrame and update methods + GUI elements. Do I create a instance variable of View in my Game class? Do I Create the variable in the Main method?

Basically, I really am just trying to progress past learning the "actual language" and more of the technique and structure behind professional programs. I've been looking at the structure of Notch's Minicraft (not minecraft!) source code if that helps?


texts: How to Change an Icon based on what Collider the Player Hits

texts: So I have a 2D platform game where a player goes around collecting fruit but currently I only have one icon. Currently I use an image on a canvas to display the fruit image. How can I make the UI image change based on what fruit the player collects?


texts:
I'm working on a browser-based RTS, and we are targeting 10k+ users with multiple towns per user.

I have the following table townresources in which I store every resource value for every town ID:

CREATE TABLE IF NOT EXISTS `townresources` (
  `townResourcesId` int(10) NOT NULL AUTO_INCREMENT,
  `userId` int(10) NOT NULL,
  `resourceId` int(10) NOT NULL,
  `townId` int(10) NOT NULL,
  `balance` decimal(8,2) NOT NULL,
  `resourceRate` decimal(6,2) NOT NULL,
  `lastUpdate` datetime NOT NULL,
  PRIMARY KEY (`resourceId`,`townId`,`townResourcesId`,`userId`),
  KEY `townResources_userId_users_userId` (`userId`),
  KEY `townResources_townId_towns_townId` (`townId`),
  KEY `townResourcesId` (`townResourcesId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Stores Town Resources' AUTO_INCREMENT=9;

I'm a bit reserved about performance impact for a large amount of users. I'm thinking about moving the balance for resources to the towns table, and the general value of a resource to a PHP file. Is this a better option?


texts: Unable to get accurate y position on terrain to spawn object

texts:
all I am trying to spawn some crabbies and can't seem to get an accurate y height to spawn.
I have a terrain created with GAIA Pro 2 and have tried a few things to get an accurate y value. When trying to get the y from the terrain data I keep getting a 0 for example :
        //newCrabStartPos.y = mainIslandTerrain.terrainData.GetHeight((int) rayPosition.x, (int) rayPosition.z); //getYPositionFromRay(rayPosition) + 2.5f;

Here is my current implimintation :
   IEnumerator SpawnCrab()
{
    while(spawnedCrabbies <= waveCount)
    {
        GameObject instance = Instantiate(Resources.Load("Whakin_Crab", typeof(GameObject))) as GameObject;
        instance.transform.position = SetStartPosition();

        spawnedCrabbies += 1;
        yield return new WaitForSeconds(spawnRate);
    }
}

Vector3 SetStartPosition()
{

    float minDistanceAwayFromGoal = 10f;
    float maxDistanceAwayFromGoal = 50f;

    float xpos = Random.Range(-1f, 1f) <= 0 ? Random.Range(-minDistanceAwayFromGoal, -maxDistanceAwayFromGoal) : Random.Range(minDistanceAwayFromGoal, maxDistanceAwayFromGoal);
    float zpos =  Random.Range(-1f, 1f) <= 0 ? Random.Range(-minDistanceAwayFromGoal, -maxDistanceAwayFromGoal) : Random.Range(minDistanceAwayFromGoal, maxDistanceAwayFromGoal);
    Vector3 newpos = new Vector3(xpos, 0, zpos);

    Vector3 rayPosition = new Vector3(xpos, 100, zpos);
    Vector3 newCrabStartPos = new Vector3(newpos.x, 15, newpos.z);

    newCrabStartPos = newCrabStartPos + goal.transform.position;
    newCrabStartPos.y = getTerrainDistanceFromRay(rayPosition); // mainIslandTerrain.terrainData.GetHeight((int) xpos, (int) zpos); //getYPositionFromRay(rayPosition) + 2.5f;

    return newCrabStartPos;
}

float getTerrainDistanceFromRay(Vector3 drawFromPosition)
{
    RaycastHit hit = new RaycastHit();

    if (Physics.Raycast(drawFromPosition, Vector3.down, out hit, 100))
    {

        return (100 - hit.distance); // collider.gameObject.transform.position.y;
    }

    return 0;
}


texts: How to Slice the external Spritesheet programmatically by using C# in Unity

texts:
I have a sprite sheet like this:

I am using Unity Engine to develope my game. I would like to load this external spritesheet outside and slice it as Grid type programmatically instead of using Sprite Editor in Unity.
I would like to find a way to do it by using C# scripting. Because my game would have more than 5 heroes with 10 animations per hero for next updates in my game.


texts: Game mechanics for a persistent real-time strategic/tactical game

texts:
I am designing a game based around a fairly realistic simulation of 'Age of sail'-like trading and combat, and I  am currently trying to decide whether to make the game a limited on-line application, in which the game world exists only while all the players - 2 to 8 of them - are all online, or a persistent real-time mmo application, in which game events occur on a set schedule.  As a game for a small number of players, uninteresting events could be time-accelerated away.

The trouble with a real-time MMO is that the world objects would be persistent, yet the players would be transient.  Since in-game encounters and combat would take place on a schedule determined by the actions of all the players, not just those that happen to be online, players could easily miss an encounter or battle in which their vessel happened to be involved - or at least could be involved.

An idea I had for the MMO version was that otherwise idle time could be spent in training - which would be simulated, not merely administrative, and that active crew positions such as gunners, helmsmen, marines and officers could be filled by players, so one ship might have many players online in engagements, each contributing to the success - or otherwise - of the battle.  These positions would be filled by players whose vessels were all engaged in uninteresting travel or laid up for repairs, using a matchmaking system to match the players' observed skill to that of the NPC into whose shoes they would be stepping.  NPC skill progression would be based upon the actual skill improvement of the players who step into the role.

What other game mechanics could allow a game such as this to be playable as a persistent real-time mmo, especially when vessels could spend a long time in transit, doing nothing much of interest?


texts: Implementing a FSM with ActionScript 2 without using classes?

texts:
I have seen several references of A.I. and FSM,
but sadly I still can't understand the point of an FSM in AS2.0.
Is it a must to create a class for each state?

I have a game-project which also it has an A.I.,
the A.I. has 3 states: distanceCheck, ChaseTarget, and Hit the target.

It's an FPS game and played via mouse.

I have created the A.I. successfully, but I want to convert it to FSM method...

My first state is CheckDistanceState() and in that function I look for the nearest target and trigger the function ChaseState(), there I insert the Hit() function to destroy the enemy,

The 3 functions that I created are being called in AI_cursor.onEnterframe.

Is there any chance to implement an FSM without the need to create a class?
From what I've read before, you have to create a class. I prefer to write the code on frames in flash and I still don't understand how to have external classes.


texts: How can I constrain the player's movement to horizontal or vertical?

texts:
This is one of my first coding projects, so apologies for beginner questions....

My player controller script uses the below code, but I want to limit movement to horizontal and vertical only. No diagonal movement.

Here's how it looks:

public class PlayerController : MonoBehaviour
{
    //I’m moving the rigid body to move the player
    public Rigidbody2D theRB;

    //lets me change player's move speed in unity editor
    public float moveSpeed;

    // Update is called once per frame
    void Update()
    {
        theRB.velocity = new Vector2( Input.GetAxisRaw("Horizontal")
                                    , Input.GetAxisRaw("Vertical")) * moveSpeed;

I've tried the below code to only accept one command at a time by using an if statement, however, with this new code, the player doesn't stop walking once the key is no longer pressed.

Just wondering if someone could point me in the direction of what I'm doing wrong?

// Update is called once per frame
void Update()
{
    if (Input.GetAxisRaw("Horizontal") == 1 || Input.GetAxisRaw("Horizontal") == -1)
    {
        theRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), 0) * moveSpeed;
    }

    if (Input.GetAxisRaw("Vertical") == 1 || Input.GetAxisRaw("Vertical") == -1)
    {
        theRB.velocity = new Vector2(0, Input.GetAxisRaw("Vertical")) * moveSpeed;
    }

thanks!


texts: Error instantiating Texture2D in MonoGame for Windows 8 Metro Apps

texts:
I have an game which builds for WindowsGL and Windows8. The WindowsGL works fine, but the Windows8 build throws an error when trying to instantiate a new Texture2D.

The Code:

var texture = new Texture2D(CurrentGame.SpriteBatch.GraphicsDevice, width, 1); // Error thrown here...
texture.setData(FunctionThatReturnsColors());

You can find the rest of the code on Github.

The Error:

SharpDX.SharpDXException was unhandled by user code
  HResult=-2147024809
  Message=HRESULT: [0x80070057], Module: [Unknown], ApiCode: [Unknown/Unknown], Message: The parameter is incorrect.

  Source=SharpDX
  StackTrace:
       at SharpDX.Result.CheckError()
       at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription& descRef, DataBox[] initialDataRef, Texture2D texture2DOut)
       at SharpDX.Direct3D11.Texture2D..ctor(Device device, Texture2DDescription description)
       at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height, Boolean mipmap, SurfaceFormat format, Boolean renderTarget)
       at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height)
       at BrewmasterEngine.Graphics.Content.Gradient.CreateHorizontal(Int32 width, Color left, Color right) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Graphics\Content\Gradient.cs:line 16
       at SampleGame.Menu.Widgets.GradientBackground.UpdateBounds(Object sender, EventArgs args) in c:\Projects\Personal\GitHub\BrewmasterEngine\SampleGame\Menu\Widgets\GradientBackground.cs:line 39
       at SampleGame.Menu.Widgets.GradientBackground..ctor(Color start, Color stop, Int32 scrollamount, Single scrollspeed, Boolean horizontal) in c:\Projects\Personal\GitHub\BrewmasterEngine\SampleGame\Menu\Widgets\GradientBackground.cs:line 25
       at SampleGame.Scenes.IntroScene.Load(Action done) in c:\Projects\Personal\GitHub\BrewmasterEngine\SampleGame\Scenes\IntroScene.cs:line 23
       at BrewmasterEngine.Scenes.Scene.LoadScene(Action`1 callback) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Scenes\Scene.cs:line 89
       at BrewmasterEngine.Scenes.SceneManager.Load(String sceneName, Action`1 callback) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Scenes\SceneManager.cs:line 69
       at BrewmasterEngine.Scenes.SceneManager.LoadDefaultScene(Action`1 callback) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Scenes\SceneManager.cs:line 83
       at BrewmasterEngine.Framework.Game2D.LoadContent() in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Framework\Game2D.cs:line 117
       at Microsoft.Xna.Framework.Game.Initialize()
       at BrewmasterEngine.Framework.Game2D.Initialize() in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Framework\Game2D.cs:line 105
       at Microsoft.Xna.Framework.Game.DoInitialize()
       at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
       at Microsoft.Xna.Framework.Game.Run()
       at Microsoft.Xna.Framework.MetroFrameworkView`1.Run()
  InnerException:

Is this an error that needs to be solved in MonoGame, or is there something that I need to do differently in my engine and game?


texts: Surface shader with VertexLit causes black object

texts:
I wrote the simplest possible surface shader:

Shader "SimpleSurf" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {
        Tags {"RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

When the "Forward" rendering path is enabled the object looks fine!

But when the "Vertex lit" rendering path is enabled, it looks became black:

Why it happened? How can I use surface shaders (or maybe write a Vertex/Fragment shader which will consider spot lights) which do some effects in VertexLit path?


texts: Texture filtering: Is the minification or the magnification filter used when rendering at the exact texture size?

texts:
Suppose you have a texture where the minification filter is linear, but the magnification filter is nearest-neighbor (point filtering). If the texture is rendered at exactly 1:1 pixels, but at a non-whole-number pixel position, it is being neither minified or magnified.

Is there a convention for whether the min or mag filter will be used? What is the justification?


texts: Are there many games involving the manipulation of water?

texts:
I'm in the very, very early brainstorming stages of a game which centers around the manipulation of water and the terrain around it. (i.e., changing the water's state between solid, liquid, gas; building up or tearing down hills to control its flow; and so forth.)  I'm not yet sure if it should be a puzzle game, a platformer, or what.

Usually, when brainstorming a game, I try to find games with similar mechanics to see what is done well, poorly, etc.  But this time, I'm having trouble thinking of any games that use the flow of water as a primary mechanic.  (Pipe Dream is about all that comes to mind.)

So, I'm asking around...  does anyone know of any games where controlling water is a major aspect?  Is there much reference material (of any kind) on the subject of water as a gameplay mechanic?  Or any ideas where to look?

Thanks


texts: How to create a hexagon world map in PHP from a database for a browser based strategy game

texts:
I'm trying to create a hexagon world map for my PHP browser based strategy game. I've created a table in my database with the following data per row: id, type, x, y and occupied. Where type is the kind of tiles, which are defined in numbers. For example, 1 is grass. The map itself is 25 x 25.

I want to draw the map from the database with clickable tiles and the possibilty to navigate through the map with arrows. I don't really have a clue on how to start with this and any help would be appreciated.


texts:
I'm trying to generate some simple planets in OpenGL using libnoise (including noiseutils), but the terrain is not correctly connecting where the sphere "completes itself" and I was wondering if someone could explain to me why this is happening and/or point me in the direction to solving this little problem.

I'm generating spheres with a slightly adapted version of this algorithm, with this being my full code:

static void GenerateSphere( VertexBuffer& vertices, IndexBuffer32& indices, uint rings, uint sectors, float radius, const HeightModule* heights )
{
    static const double pi   = glm::pi<double>();
    static const double pi_2 = glm::half_pi<double>();

    // texture-coordinate conversion helpers
    const float rr = 1.0f / float( rings   - 1 );
    const float ss = 1.0f / float( sectors - 1 );

    // clear buffers
    vertices.Clear();
    indices.Clear();

    // iterate through each ring and sector to create the vertices
    float height = 0;
    Vertex v;
    for ( uint r = 0; r < rings; ++r )
    {
        for ( uint s = 0; s < sectors; ++s )
        {
            // calculate point
            glm::vec3 point(
                float( cos( 2 * pi * s * ss ) * sin( pi * r * rr ) ),
                float( sin( -pi_2 + pi * r * rr ) ),
                float( sin( 2 * pi * s * ss ) * sin( pi * r * rr ) )
            );

            // set vertex data
            height = radius + heights->GetHeight( s, r );
            v.TexCoord = glm::vec2( s * ss, r * rr );
            v.Normal   = point;
            v.Position = point * height;
            vertices.Add( v );

            // set index data
            indices.Add( r * sectors + s );
            indices.Add( r * sectors + ( s + 1 ) );
            indices.Add( ( r + 1 ) * sectors + ( s + 1 ) );
            indices.Add( ( r + 1 ) * sectors + s );
        }
    }
}

VertexBuffer and IndexBuffer32 are simple wrappers for their OpenGL counterparts, and HeightModule is a wrapper for some libnoise and noiseutils functions (like NoiseMap, NoiseMapBuilderSphere, and some noise modules).

To illustrate what I mean by heights not matching where the sphere "completes itself," here is a screenshot:

As you can see on the left, the vertices do not quite reach each other (it's like this all the way from pole to pole) and the texture coordinates are messed up on the connecting lines. The blue line you see on the right extends from the origin all the way to the north pole, and after some debugging I've found that all of the vertices generated when r == 0 are the same with the position being [0,-radius,0] and the normal being [0,-1,0] (the texture coordinates appear to the correct though, as they all differ). I suspect the terrain problem is caused by this, but I have no clue how I would go about fixing that.


texts: What type of legal entity do I need for my game company in the USA?

texts:
I'm the leader of a group of 4 of us that are contributing to a game and it has come to my attention that we will eventually need some kind of official title or something along those lines. We've agreed on a name, and we've already got a domain name and several back-end resources that I've set up under the brand as well.

I'm curious as to the steps needed to be taken to make it "official" and protect my assets. Is this something I'm best off worrying about closer to release?

I've looked at this post, and I was also taking a look at this page. However, I want some straight answers from people who may have been down similar roads in the past.


texts: How to find a safe path for an AI snake?

texts:
I have been working on a game in which a player can compete with a snake ai to get the most apples.  The current path finding technique i use (A* Pathfinding) works fine. But I am struggling with coming with an effective way to make sure that the AI snake does not go for an objective that leads to it trapping itself. Consider that the snake can teleport and that there may be max 4 apples on the map at any given time. The decision tree I am trying to create looks somewhat like this:

If path to goal is safe : go for apple!
Else check next apple until a safe path is found or all apples are checked.
If no path to any apple is safe including the paths produced if teleportation is possible, Then find the farthest path to the tail and remain chasing the tail until a safe path to an objective becomes available. If no path to tail is found : stall until death!

The problem is that it is really hard to find a fast and efficient way to determine if a path is safe!

My question is: what is a good way to determine if a path into an enclosed area is safe given that you cannot take the same path back out of that area?


texts: Why not use vectors to represent orientation?

texts:
From what I've read, people mostly use either quaternions or 3x3 matrices to represent 3D orientations, while plain vectors are used for angular velocity/momentum.
Since we can use vectors to represent angular velocities, why can't we also use vectors to represent orientations? Are there any specific reasons or is it simply less convenient?

EDIT: Just to clarify, I mean using a 3D vector to represent a rotation around an arbitrary axis, with the magnitude being the rotation.


texts:
I'm currently implementing an A* Algorithm for my Unity project. I found this entry on stackoverflow, but its not telling me how to solve my problem.
https://stackoverflow.com/questions/32205891/a-star-algorithm-in-a-3d-configuration-space
I'm not sure about the math required to calculate the distance cost correctly. How to properly implement this in 3-dimensional space?
In 2D space it is clear how to implement:
public static int CalculateDistanceCost(int3 a, int3 b)
{
    int xDistance = math.abs(a.x - b.x);
    int yDistance = math.abs(a.y - b.y);
    int remaining = math.abs(xDistance - yDistance);

    return 14 * math.min(xDistance, yDistance) + 10 * remaining;
}

However in 3d space it is unclear to me how to calculate it:
public struct AStarMath
{
    public static int CalculateDistanceCost(int3 a, int3 b)
    {
        int xDistance = math.abs(a.x - b.x);
        int yDistance = math.abs(a.y - b.y);
        int zDistance = math.abs(a.z - b.z);
        int remaining = math.abs(xDistance - yDistance - zDistance);

        return 14 * math.min(math.min(xDistance, yDistance), zDistance) + 10 * remaining;
    }
}

My neighbour cells are set up as follows:
int3 neighbours = new int3[]
{
                            //X(width),y(height),z(depth)
    new int3(-1, -1, -1), //Left, Bottom, Front
    new int3(0,  -1, -1), //Middle, Bottom, Front
    new int3(+1, -1, -1), //Right, Bottom, Front

    new int3(-1, 0, -1),  //Left, Middle, Front
    new int3(0,  0, -1),  //Middle, Middle, Front
    new int3(+1, 0, -1),  //Right, Middle, Front

    new int3(-1, +1, -1), //Left, Top, Front
    new int3(0,  +1, -1), //Middle, Top, Front
    new int3(+1, +1, -1), //Right, Top, Front

    new int3(-1, -1, 0),  //Left, Bottom, Middle
    new int3(0,  -1, 0),  //Middle, Bottom, Middle
    new int3(+1, -1, 0),  //Right, Bottom, Middle

    new int3(-1, 0,  0),  //Left, Middle, Middle
    //Middle, Middle, Middle (0,0,0) -> dont add, were already here
    new int3(+1, 0,  0),  //Right, Middle, Middle

    new int3(+1, +1, 0),  //Left, Top, Middle
    new int3(0,  +1, 0),  //Middle, Top, Middle
    new int3(+1, +1, 0),  //Right, Top, Middle

    new int3(-1, -1,+1),  //Left, Bottom, Back
    new int3(0,  -1,+1),  //Middle, Bottom, Back
    new int3(+1, -1,+1),  //Right, Bottom, Back

    new int3(-1,  0,+1),  //Left, Middle, Back
    new int3(0,   0,+1),  //Middle, Middle, Back
    new int3(+1,  0,+1),  //Right, Middle, Back

    new int3(-1, +1,+1),  //Left, Top, Back
    new int3(0,  +1,+1),  //Middle, Top, Back
    new int3(+1, +1,+1),  //Right, Top, Back
};

As you can see in this image, my enemy (magenta) now takes a weird path, but will always find a path towards target (blue).


texts: How do I import multiple animations into the same file in Unity?

texts: I have hit a major stump in my development: applying transitioning animations to the same model. I have learned how to do a single animation with keyframes, but have no clue on what to do with more than one. I tried importing different animations seperately and applying them to the same model, but it didn't work. How can I get past this stumbling block?


texts: How to force a translation to go through an exact point?

texts:
I have a camera object with a script that will whether translate it with a set speed, or stop it. I also have 7 "checkpoints", where there are 7 different quads, who will stop the camera whenever the camera reaches them.

The problem here is that in my code :

void Update() {

if (scoreholder.CheckScore()<scoretimer) {
//if the current score is less than set X score

        if (killcam.transform.position.y == quadholder.y) {
//and if the camera's position equals the position of the generic quad *PROBLEM HERE*

            killcam.GetComponent<cameraUp> ().SetCam (true); //stop the cam

            while (scoreholder.CheckScore () < scoretimer) { // do stuff

                offset = mr.material.mainTextureOffset;
                offset.y += offsetSpeed * 0.1f;
                mr.material.mainTextureOffset = offset;

                break;
            }
        }

    }

else { //once the score is not less than the desired X score, move the cam
        killcam.GetComponent<cameraUp> ().SetCam (false);
    }

}

So my problem here is that this line of code if (killcam.transform.position.y == quadholder.y) never happens, the translation skips some values, and the camera doesn't hit the exact quad spot. I tried to use > instead of ==, but I ran into another problem, is that after the 3rd quad, since my camera speed increases in time, the code apparently doesn't get processed fast enough, and my camera goes beyond the 4th,5th,6th, and 7th quad without stopping.

I have already tried Vector3.Lerp, and it gives me almost the same result, if I lerp between the beginning and the end of the track, I have to do it with an extremely small fraction, and I can't have my camera move at that speed.


texts: Physics not working when game is running on device Unity

texts:
I have my bouncing ball game. The ball bounces up when it hits the ground and when it hits the left wall it changes direction to right and when it hits the right wall it changes direction to left and continues to bounce. Now the problem is that sometimes physics system does not register the collision between the ball and left/right wall, so the ball just passes through them and goes out of play, I have no idea whats going on. I will attach two pictures, one from game view and other from scene view.

Again I say everything works great, the ball bounces and hits the wall then changes the direction but sometimes the collision between a wall and a ball is not registered and the ball just passes through the wall like there is no physics and goes out of camera view.


texts:
I'm creating a simple level-up system and I'm looking to base the stats gain on curves so I can tweak them easier, I know it's a math function, but I have no idea what to search for.

I need to create this curve and get the value every x increment.

the engine I'm using is Ren'py and the language python. if you can tell me the terms to search for, I might be able to find something on the topic.


texts: I'm kinda new to the programming scene. I'm still a high school student but I want to be a game designer so I'm studying independently before I graduate to get an edge. The issue with this is that although I have learned some programming, I can't follow all of the technical terms that get thrown around on the game dev forums. One of the terms that gets used a lot is cache, and I'm wondering what that means. Outside of programming it means a secret stash of something you don't want others to know about, which could be referring to things like AI, login info or, something like that. I would like a more specific answer if anyone would be willing to give the time.


texts: How to trigger onclick for Unity Selectable by script?

texts:
As title, I know Button can be triggered onclick by button.onClick.Invoke();
But how to simulate onclick event of Selectable?
Thanks for the help.


texts: How can I design the environments in my game to be memorable and unique?

texts:
I've always been a fan of the Metroid series, and more generally nowadays, the metroidvania genre. One thing that I've loved, and most others have praised highly, are the unique and diverse environments and levels you can find in such games. Being able to tell exactly what room someone is in from a simple screenshot is a prime staple to such things.

I have been working on a 2D metroidvania game that's intended to be kind of my personal tribute to the genre, but I feel like I may have put myself in a bit of a corner conceptually. The game takes place on a barren, lifeless planet that's being harvested for resources by a sprawling autonomous mining/factory complex. Throughout the game, you travel throughout the complex, visiting each of the sites that make it up and gaining upgrades to become powerful enough to take down the AI at the center of it all (yeah, original, I know).

So, the conceptual corner... I'll be blunt. As you can probably tell from the title, and the setup in the first paragraph, I'm seriously worried that the areas in my game are going to feel too "same-y" and repetitive. I mean, and it's justified too: my selections of environments are "lifeless, rocky landscape", "lifeless, rocky caves", and "industrial metal corridors", and my selection of enemies consists of "robots", "more robots", and "different, bigger robots". I mean, it's hard to have different environments when the setting you're in has no life to support an "environment". But, I know it can be pulled off. Just look at Hero Core. It manages to pull off distinct and unique areas with much of the same restrictions I have, and with only just two colors to boot!

In closing, and yes, this is just basically an expanded restatement of the title, what are some things I can do to make the areas in my game feel markedly distinct from eachother, despite most of them having a common overarching aesthetic?


texts:
I never did physics in my life and this is really hard for me. I am currently trying to implement movement in the X and Y axis of a plane, in a video game I am making.

What I want to do is, given a starting angle and a velocity, and the value of gravity, calculate in different points of time the current angle and the displacement in X and Y.

So, lets say, my current velocity is 4 units / second and my current angle is 30 degrees and my gravity is 9.8 u/s, I want to pass an argument in seconds and calculate the final angle, velocity, and the amount of X and Y the body moved.


texts:
I wonder if this gameloop in Java is accurate to give around 60 frames a second, is it?

public void run() {
    long then = System.nanoTime();
    long targetFPS = 60;
    Timer timer = new Timer();

    while(running){
        long now = System.nanoTime();
        long updateLength = now - then;
        long update = updateLength / targetFPS;
        then = now;
        System.out.println(update);
        if(update >= 16){
            render();
            tick();
            System.out.println(updateLength);
        }
    }
}


texts: Swift - Why does my SKShapeNode pass through an object, pausing briefly beforehand?

texts:
The code below when run on a device that’s flat on the table shows a red circle (the 'ball') and a line.

When I gently tip the device the circle moves towards the line. When it reaches the line, it stops which is the expected and desired behaviour.

BUT if I keep tipping, the circle moves through the line. I’ve been trying for 2 days to work out why grrr I just want the circle to hit the line and not go through it.

Any ideas? Anything to do with the line being an 'edge'?

Cheers,
Andy

import SpriteKit
import CoreMotion

class GameScene: SKScene, SKPhysicsContactDelegate {
    var ball : SKShapeNode!
    var line : SKShapeNode!
    var motionManager = CMMotionManager()
    var destX : CGFloat!
    var destY : CGFloat!
    let ballRadius = CGFloat(20.0)

override func didMoveToView(view: SKView) {
    backgroundColor = SKColor.whiteColor()
    physicsWorld.gravity = CGVector(dx: 0, dy: 0)
    physicsWorld.contactDelegate = self

    ball = SKShapeNode(circleOfRadius: ballRadius)
    ball.fillColor = UIColor.redColor()

    ball.position = CGPoint(x: frame.size.width/4, y: frame.size.height / 2)
    destX = frame.size.width/4
    destY = frame.size.height / 2
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)
    addChild(ball)

    line = SKShapeNode()
    var lineStart = CGPoint(x: frame.size.width/2, y: 0)
    var lineEnd = CGPoint(x: frame.size.width/2, y: frame.size.height)
    var linePoints = [lineStart, lineEnd]
    var linePos : CGMutablePathRef = CGPathCreateMutable()
    CGPathAddLines(linePos, nil, linePoints, 2)
    line.path = linePos
    line.strokeColor = UIColor.blackColor()
    line.physicsBody = SKPhysicsBody(edgeFromPoint: lineStart, toPoint: lineEnd)
    addChild(line)
}

override func update(currentTime: NSTimeInterval) {
    moveBall()
}

func moveBall() {
    motionManager.startAccelerometerUpdatesToQueue(
    NSOperationQueue.currentQueue(), withHandler: {
        data, error in
        var currentX = self.ball.position.x
        var currentY = self.ball.position.y
        self.destY = currentY - CGFloat(data.acceleration.x * 100)
        self.destX = currentX + CGFloat(data.acceleration.y * 100)
        }
    )
    ball.position = CGPoint(x: destX, y: destY)
    }
}

import UIKit
import SpriteKit

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    let skView = self.view as! SKView
    let scene = GameScene(size: CGSizeMake(
    skView.bounds.size.width, skView.bounds.size.height))
    skView.showsFPS = true
    skView.showsNodeCount = true
    skView.ignoresSiblingOrder = true
    scene.scaleMode = .AspectFill
    skView.presentScene(scene)
}

override func prefersStatusBarHidden() -> Bool {
    return true
}
}

EDIT: many thanks to Attackfarm :)

I changed the moveBall() function as follows:

func moveBall() {
    motionManager.startAccelerometerUpdatesToQueue(
        NSOperationQueue.currentQueue(), withHandler: {
            data, error in
                self.ball.physicsBody!.applyForce(CGVector(dx: -data.acceleration.x*100,
                        dy: data.acceleration.y*100))
        }
    )

which in this proof of concept demonstrates what I needed. Thanks again!


texts: How to convert a number from one min\max set to another min\max set?

texts: I'm doing terrain generation and I have a perlin library that is giving me random numbers between -1 and +1. I want to convert this to the scale of 0-255. What is the proper way to do this?


texts: How heavy is a scene load in Unity assuming all referenced objects are in memory?

texts:
From what I understand, resources that are local to a particular scene( not a prefab, or texture, material asset etc ) are embedded in the scene file itself, while external resources are just referenced and loaded if needed. The game I'm working on requires all scene be loaded from an asset bundle. Which means by the time the level is loaded, all data should be in memory.

In order to show relatively accurate load progress, I sum of the total bytes of all the needed asset bundles to load the level and divide that by the (approximate) number of bytes loaded so far( calculated using the file size of the asset bundle in bytes multiplied by Unity's AssetBundleRequest.progress value ).

However, this isn't possible with Application.LoadLevel since there's no way to weigh how long it might take relative to the time it took to load the asset bundles.

So, my question is, does Application.LoadLevel take long enough to be an issue if ignored? The presence of an async version of this method leads me to believe there is some need for this. That might only apply for scenes that were built into the game rather than into an asset bundle though.


texts: Performace benchmark between a C++ and a C# renderer engine?

texts:
I want to create a performant 3d renderer for a tech demo at the university workshop. The engine will basically render a forested backdrop, in a small octrant.

I am thinking of writing the engine in a managed language, but I am in a dilema about a possible performace handicap.

Google search just gave some raw benchmarks, with C/C++ winning by vast margins. But I need some performance benchmarks, especially in these kind of softwares... (renderers)

Also, if there are performance slogs, what are their immidiate reasons ? (leaving out GC)


texts:
I want to choose from 4 enemies using random and present it on scene. For that purpose I've made this:

func enemyPicker() -> SKSpriteNode {
var enemyArray = [mouse, robot, drone, block, bird]
var countArray = UInt32(enemyArray.count)
var pickOneEneny = arc4random_uniform(countArray)
var randomElement = Int(pickOneEnemy)

return enemyArray.randomElement
}

But Xcode says to me that SKSpriteNode does not have a member named randomElement. And it surely doesn't, but how would I say to my function that I need it to pick and assign that random Int to an actual enemy from array?

My SpriteNodes are declared like this. Example:

var mouse = SKSpriteNode()
let mouseAtlas = SKTextureAtlas(named: "mouse")
var mouseArray = [SKTexture]()
mouseArray.append(mouseAtlas.textureNamed("mouse_0"));
mouseArray.append(mouseAtlas.textureNamed("mouse_1"));
mouseArray.append(mouseAtlas.textureNamed("mouse_2"));

mouse = SKSpriteNode(texture: mouseArray[0]);
self.mouse.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMidY(self.frame) - 138)
self.mouse.size = CGSizeMake(self.mouse.size.width, self.mouse.size.height + mouse.size.height / 2)

self.mouse.name = "mouse"
self.addChild(mouse)

I also tried to change -> SKSpriteNode to SKTexture, String and "< T >" and had not any luck with it.


texts:
I'm quite new to java.

I was developing a game using java and I realized that the position of pack() method can influence rendering. For instance:

Frame Class

public class Frame {
    public Frame(int width, int height, Game game) {
        JFrame frame = new JFrame("Practice Game");

        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        frame.pack();  // pack method is used before adding game component to frame
        frame.add(game);
    }
}

Game Class (I skipped few methods for simplicity)

public class Game extends Canvas implements Runnable {
    // Dimension
    public static final int WIDTH = 320;
    public static final int HEIGHT = 320;

    public Game() {
        new Frame(WIDTH, HEIGHT, this);

        menu = new Menu(WIDTH, HEIGHT);

        start();
    }

    public void render() {
        BufferStrategy bs = this.getBufferStrategy();

        if (bs == null) {
            this.createBufferStrategy(3);
            return;
        }

        Graphics2D g = (Graphics2D) bs.getDrawGraphics();

        menu.render(g);

        g.dispose();
        bs.show();
    }

    public static void main(String[] args) {
        new Game();
    }

This set of code results in making an empty frame without any component displayed.

However, when I tried putting pack method after I added game component to the JFrame, it successfully displayed what I intended to display.

I heard that pack() method is used to pack the components within the JFrame based on the component’s preferred sizes. However, I don't understand how the position of pack() method could influence the entire rendering (only displaying an empty frame).

Also, the actual size of frame doesn't match the dimension that I assigned to the frame. To illustrate this:

Menu Class

public class Menu {
    public Menu(int width, int height) {
        this.width = width;
        this.height = height;

        squareSize = 64;

        squareRowNum = height / squareSize;
        squareColNum = width / squareSize;
    }

    public void render(Graphics2D g) {
        drawBackground(g);
    }

    public void drawBackground(Graphics2D g) {
        for (int i = 0; i < squareRowNum; i++) {
            for (int j = 0; j < squareColNum; j++) {
                g.setColor(Color.black);
                g.setStroke(new BasicStroke(3));
                g.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
                g.setColor(Color.white);
                g.fillRect(j * squareSize, i * squareSize, squareSize, squareSize);
            }
        }
    }

When running these 3 classes together, it display:

The rectangle box at the bottom are cut off instead of fully displaying 5 * 5 rectangles (each rectangles has dimension of 64, 64 and the frame size is supposedly 320, 320). I assumed that it's because I'm using mac. I think this can also be fixed using pack() method but I don't know how.


texts:
I am working on re-writing an old game, and have faced some issues with the older images that were used, the first thing we done was convert all the old images and set the alpha channel on black pixels so they are transparent, and then built our image libraries. However, the animated images have had some conversion issues it appears the edges of the images were not all set to true black so the conversion never set the transparency on these pixels. The value on the edges varies between R0 G0 B1-16 we have seen but we can't be sure as there is 1000s of images.

If we use additive blending it allows us to blend without showing the noisy outline but the additive blending does not display the images exactly how they should be to reproduce the old style of the game of course.

Question is, what options are available to either fix the image, or render it properly at run time using a HLSL.

I am hesitant to run a conversion on the known black ranges as we might miss a lot out and extending the range might set stuff we should set wrongly. Has anyone faced this before and how did you solve it?


texts: How to set up Cocos2d-x for visual studio?

texts:
I want to make a cocos2d-x game. I read you can use any IDE, so I was planning to use Microsoft Visual Studio 2015, since I want to make my game primarily for Windows. I have been searching for tutorials, but i couldn't find any. It'd be great if someone wrote a step-by-step guide on how to set it up.

Thanks in advance.


texts:
In the past I've done cooldowns as a specific time in ms, but I was thinking isn't having tick based cooldowns better. This would be more accurate and efficent(not sure).

The bad side I can think about is that if the tick rate is increased, it would affect the game logic. While having a base update rate and a multiplier(that can be applied to everything that is tied to tick rate) would probably fix this, I am not sure if this is a good approach.


texts: How do you handle 'move to mouse', if the player is already at the mouse?

texts:
I'm making a top-down-2D game. When my player moves, the cursor does not move with it. In my game, the player moves by facing the cursor and then walking toward it. This means that eventually, the player will reach the cursor and then glitch out.

How do I handle player movement when they reach the mouse?


texts: Function Not Storing New Value of Variables?

texts:
I'm currently building a small-scope RPG and running into an issue with modifying variables.  My goal is to alter my character's stats when I run a procedure to change their equipment.  My code is as follows:
public class Player: MonoBehaviour   {
    //Base stat variables
        public static int PAtk = 12;
        public static int PDef = 6;
    //Battle-exclusive stats.  Will have equipment added onto them.
        public static int Attack = PAtk;
        public static int Defense = PDef;
    //Equipment variables.
        public string weapon;
        public string armor;

    private void Awake()
    {
        //Get equipment
        EquipWeapon("Bronze Sword");
        EquipArmor("Bronze Armor");
    }

void EquipWeapon(string WeaponName)
    {
        weapon = WeaponName;
        EquipmentManager.GetComponent<Equipment>().EquipStatIncrease(PAtk, Attack, PDef, Defense, WeaponName);
    }
void EquipArmor(string ArmorName)
    {
        armor = ArmorName;
        EquipmentManager.GetComponent<Equipment>().EquipStatIncrease(PAtk, Attack, PDef, Defense, ArmorName);
    }
}

public class Equipment: MonoBehaviour  {
    //Create dictionary to give each weapon a key ID.  This will be used for calling items in another array.
        Dictionary<string, int> WeaponDictionary = new Dictionary<string, int>();
    //Create weapon array for stats.
    public int[,] WeaponStats;

    // Start is called before the first frame update
    void Awake()
    {   //Declare weapon IDs
            WeaponDictionary.Add("Bronze Sword", 0);
            WeaponDictionary.Add("Bronze Armor", 1);
        //Declare stat array
        //Table: ID, Atk, Def
        WeaponStats = new int[,]
        {
            {0,4,0},
            {1,0,4}
        };
    }

    public void EquipStatIncrease(int BaseAtk, int BattleAtk, int BaseDef, int BattleDef, string Equipment)
    {
        BattleAtk = BaseAtk + WeaponStats[WeaponDictionary[Equipment], 1];
        Debug.Log(BattleAtk + "Battle Power");
        BattleDef = BaseDef + WeaponStats[WeaponDictionary[Equipment], 2];
        Debug.Log(BattleDef + "Battle Defense");
    }
}

The general gist of it is once EquipWeapon or EquipArmor is ran, the equipment variables in the Player class will be updated.  Afterwards, another function in the Equipment class will be ran with variables from the Player class passed over, in order to be modified by the WeaponStats array.
The Debug logs in EquipStatIncrease show me that I am getting the desired results.  However, the Attack parameter that is being placed into the function is not being permanently modified.  During the first execution of the EquipStatIncrease method, I will get a result of 16 BattleAtk and 6 BattleDef, due to the weapon being equipped.  However, once it's run a second time to equip the armor, I'm shown a result of 12 BattleAtk and 10 BattleDef, even though BattleAtk should have stayed at 16.  This leads me to believe that the variables I'm trying to transform are not being modified, and I'm not sure what to do about this.  In the EquipStatIncrease parameters, BattleAtk gives the message Parameter 'BattleAtk' can be removed if it is not part of a shipped public API; its initial value is never used  However, I don't know what action to take to resolve this.
I'm aware of being able to use an int function instead of void, but unless I'm missing something, that only works if I'm trying to change one variable.  If I want to have an equipment object that affects 2 different stats at once(ex. a weapon that increases BattleAtk and BattleDef), then I don't see how an int function would work.


texts:
I tried to make a crouch system. In my script I changed .height and .center properties of collider in CharacterController component. But there are some problems. First, once I press "crouch button" collider is changing its height and center position but when I release the key the collider isn't returning to its previous state. Secondly, if I change its height and position by hand when collider is under a block, it's just stuck. How can I fix this problem?

Here's my script:

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

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour {

    public float moveSpeed;
    public float jumpForce;
    public CharacterController controller;
    public GameObject myCamera;

    private Vector3 moveDirection = Vector3.zero;
    public float gravityScale;

    public Animator anim;

    // Use this for initialization
    void Start () {
        transform.tag = "Player";
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update () {
        Vector3 forwardDirection = new Vector3 (myCamera.transform.forward.x, 0, myCamera.transform.forward.z);
        Vector3 sideDirection = new Vector3(myCamera.transform.right.x, 0, myCamera.transform.right.z);
        forwardDirection.Normalize ();
        sideDirection.Normalize ();
        forwardDirection = forwardDirection * Input.GetAxis("Vertical");
        sideDirection = sideDirection * Input.GetAxis("Horizontal");
        Vector3 directFinal = forwardDirection + sideDirection;

        if (directFinal.sqrMagnitude > 1)
        {
            directFinal.Normalize ();
        }

        if (controller.isGrounded)
        {
            moveDirection = new Vector3(directFinal.x, 0, directFinal.z);
            moveDirection *= moveSpeed;
            if (Input.GetButtonDown("Jump"))
            {
                moveDirection.y = jumpForce;
            }

            if(Input.GetButtonDown("Crouch"))
            {
                controller.height = 1f;
                controller.center = new Vector3(0f, -0.5f, 0f);
                moveSpeed = 3f;
            }
        }
        moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale * Time.deltaTime);
        controller.Move(moveDirection * Time.deltaTime);

        anim.SetBool("isGrounded", controller.isGrounded);
        anim.SetFloat("Speed", (Mathf.Abs(Input.GetAxis("Vertical")) + Mathf.Abs(Input.GetAxis("Horizontal"))));
    }
}

Thanks for any help!


texts: Batching and Z-order with Alpha blending in a 3D world

texts:
I'm working on a game in a 3D world with 2D sprites only (like Don't Starve game). (OpenGL ES2 with C++)

Currently, I'm ordering elements back to front before drawing them without batch (so 1 element = 1 drawcall). I would like to implement batching in my framework to decrease draw calls.

Here is what I've got for the moment:

Order all elements of my scene back to front.
Send order list of elements to the Renderer.
Renderer look in his batch manager if a batch exist for the given element with his Material.

Batch didn't exist: create a new one.
Batch exist for element with this Material: Add sprite to the batch.

Compute big mesh with all sprite for each batch (1 material type = 1 batch).
When all batches are ok, the batch manager compute draw commands for the renderer.
Renderer process draw commands (bind shader, bind textures, bind buffers, draw element)

Image with my problem here:

But I've got some problems because objects can be behind another objects inside another batch.

How can I do something like that?


texts: Examples of 3D space strategy with good XYZ controls?

texts:
I've been tinkering with an idea for a space sym, kind of like MOO2, writing it for mobile or browser as a way to learn Java.  Command ships and control planets, etc.  I'd love to make the game in 3d, with x, y, and z coordinates to make things more realistic, but I'm afraid that it'd be too much to implement. The engine wouldn't be any harder to code, just add another vector to the calculations, but a user interface for navigating a 3d galaxy is more difficult.  I'd prefer to keep the graphics simple, without a lot of hardcore rendering for different angles.

Does anyone have any experience designing a UI for directing units in 3D?  If I decide to go the 3D route, how should I have the player control the 3rd coordinate (the one that would come out of the screen)?  Is there a method that would allow a player to easily tell the ship how far "back" or "forward" to travel in addition to the usual up/down, right/left?


texts: Blender For Game Development, Pros And Cons

texts:
Blender is one of those applications that you either love or hate. I know it is great for 3D modeling and and animations and there is a lot said about the UI and its steep learning curve.

I am more interested in how Blender stands out as far as Game Development goes. So my question is, what would be the Pros and Cons of choosing to use Blender to develop a high performance 3D game?


texts:
I'm currently working on rope Swinging.
The Rope consists of Physics Constraints/Joints and between them the rope is rendered.
I would like align my Character's Pitch to the Rope.
I'm horribly bad at vector Math, and I have trouble finding the solution.
Here's a picture that shows what I want to achieve:

I tried using the Difference between two joints but somehow it doesn't work.
I'm using Unreal Engine if that helps.


texts: Storing stats for multiple tiers of upgrades on an item

texts:
I have one script for all my weapons (I have 3 weapons in total) and each of these 3 weapons has 3 different tiers.
I'm currently using a method to set the values, like this:
public void SetTier1Value()
{
    if (weapon1IsActive == true)
    {
        damage = 6
        fireRate = 18
        etc...
    }
    if (weapon2IsActive == true)
    {
        damage = 5
        fireRate = 20
        etc...
    }
    // and like this for the rest of the weapons and tiers
}

All the weapons and all the tiers will have the same variables, the only difference between them are the values of their stats.
I know that the way that I'm doing stuff is over-complicating a lot.
I want to fix so in the future it's easier to add new weapons and the code in general isn't that bad to change.
What I want from this script is to be able to change the values of the weapon easily by code.
What ways can I do this?


texts: Jittery Movement, Uncontrollably Rotating + Front of Sprite?

texts:
So I've been looking around to try and figure out how I make my sprite face my mouse. So far the sprite moves to where my mouse is by some vector math.

Now I'd like it to rotate and face the mouse as it moves. From what I've found this calculation seems to be what keeps reappearing:

Sprite Rotation = Atan2(Direction Vectors Y Position, Direction Vectors X Position)

I express it like so:

sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X);

If I just go with the above, the sprite seems to jitter left and right ever so slightly but never rotate out of that position. Seeing as Atan2 returns the rotation in radians I found another piece of calculation to add to the above which turns it into degrees:

sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / PI;

Now the sprite rotates. Problem is that it spins uncontrollably the closer it comes to the mouse. One of the problems with the above calculation is that it assumes that +y goes up rather than down on the screen. As I recorded in these two videos, the first part is the slightly jittery movement (A lot more visible when not recording) and then with the added rotation:

Jittery Movement

So my questions are:

How do I fix that weird Jittery movement when the sprite stands
still? Some have suggested to make some kind of "snap" where I set
the position of the sprite directly to the mouse position when it's
really close. But no matter what I do the snapping is noticeable.
How do I make the sprite stop spinning uncontrollably?
Is it possible to simply define the front of the sprite and use that to make it "face" the right way?


texts: Why do some networked games use interpolation and some use pathfinding for remote movement?

texts:
This is a bit of an open question but I'd like to see someone contribute a good reasoning for both.

For a quick example of both:

Interpolation Model

Think the Valve model where the client is receiving position updates frequently and the remotes  update their positions using interpolation on this data.

Path-finding

In this model, think the user sends a destination and everyone pathfinds to it.

What types of games are suited to each and when should one use each?


texts: How do I find the contour points of a png?

texts:
In my game, I need a way to produce convex polygons from pngs of objects.

For example, a maple leaf would result like this:

Essentially right now, the way my algorithm works is by putting all pixels that have an alpha of 255 in a list. I then create a convex hull from this list, and finally optimize the hull with a graph algorithm. The part I'm trying to optimize is the first part. I'd like a way to have the outline / border pixels of the shape rather than all pixels of the shape.

What sort of algorithm could do this?

Thanks


texts: How to rotate multi-tile structure on grid?

texts:
I need to be able to place structures in my game that span multiple tiles and can also be rotated.
My idea on how to solve this would be to use 2D arrays that hold data about the structure.
EXAMPLE: (simplified)
Crafting table layout: XOX
X - data
O - data, but also used as a pivot point
If we were to rotate it clockwise, it'd look like this:
X
O
X

My problem lies in that these positions have to be real-world coordinates, so here's the above example again but in a way that makes sense for my actual grid in-game. (replacing the X and O with coords):
(0,1)(1,1)(2,1)

And now, rotated clockwise (around the pivot point, which is (1,1)):
(1,2)
(1,1)
(1,0)

Another example purely for more information, but more complex (2x3 array):
Complex workstation ((6,4) IS THE PIVOT!):
(5,5)(6,5)(7,5)
(5,4)(6,4)(7,4)

Rotate it counterclockwise and we should get this:
(5,5)(6,5)
(5,4)(6,4)
(5,3)(6,3)

I have tried and succeeded in doing it only on a conceptual level with the "X" and "O"s, but I don't know how to implement actual coordinates.
I've never dealt with rotation matrices before so any advice, suggestion or solution on how to implement this is appreciated.


texts:
I am new to game programming and still trying to clear up my basics. I am stuck with a problem and unable to resolve on my own knowledge. I am trying to rotate a 3d cube in MonoGame (Similar to XNA) Windows Phone 8 application. The rotation works fine but it has a problem. Following is the scenario

Y axis (up/down) rotation works fine. I am able to rotate it as
many times as possible and everything works fine.
But let's say that the cube was in its default position. I rotate
my cube 180 degree on y-axis. Now when i rotate my cube on X axis. It
rotates in opposite direction. Forexample if i try to move it towards
positive x-axis it moves in negative x-axis.
If i again move the cube 180 degree in y-axis, the x-axis
rotations works fine again.

public void Update(GameTime gameTime)
{
    _userInputHandler.HandleTouchEvents();

Matrix unrotatedView = Matrix.CreateLookAt(
    cameraPosition, ModelPosition, Vector3.Up);

viewMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(Angle.Y)) *     // right/left rotation
              Matrix.CreateRotationX(MathHelper.ToRadians(Angle.X)) *   // up/down rotation
              unrotatedView;

CameraCurPos = Cube.MatrixVectorMultiply(cameraPosition, viewMatrix);

projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Game.GraphicsDevice.Viewport.AspectRatio, 1.0f, 100.0f);

}

Here is the Input handle function

public void HandleTouchEvents()
        {
            TouchCollection tc = TouchPanel.GetState();

            if (tc.Count > 0)
            {
                TouchLocation current = tc[0];
                TouchLocation prev;
                if (current.TryGetPreviousLocation(out prev))
                {
                    Vector3 newAngle = _gameEngine.Angle;
                    //newAngle.X += MathHelper.ToRadians((current.Position.X - prev.Position.X) * TURN_SPEED); // pitch
                    //newAngle.Y += MathHelper.ToRadians((current.Position.Y - prev.Position.Y) * TURN_SPEED); // yaw
                    newAngle.X += MathHelper.ToRadians((current.Position.Y - prev.Position.Y) * TURN_SPEED); // pitch
                    newAngle.Y += MathHelper.ToRadians((current.Position.X - prev.Position.X) * TURN_SPEED); // yaw

                    _gameEngine.Angle = newAngle;

                }
}
}

I know the problem is simple but i am unable to resolve it. Thanks in advance.


texts: Enhancing ambient occlusion via vert colors on vertex lit scene

texts:
We have a deformable terrain surface. Initially ambient occlusion was baked, but since the terrain can deform in real time, this approach isn't practical anymore. Therefore we used vertex paint to imitate occlusion based on the angle of the surrounding terrain vertices. We will then multiply the vertex color with the terrain texture and get a relatively cheap ambient occlusion.

Below are two examples of our terrain. The second has applied occlusion based on surrounding vertices, as mentioned before. But unfortunately it seems like the lower a set of vertices is in relation to the surrounding vertices (or the tighter the crease), the darker the vertex will be.

Vertex lighting in general works, but the results aren't as good as I expect. I wonder there is any document about a similar implementation out there.

That's our terrain without additional shading.

That's our terrain with vertex color applied to simulate ambient occlusion.


texts: How can texture packing improve performance?

texts: Let's say I let a user give my library (a GUI system) multiple textures for rendering elements. What would be the performance impact of rendering with each of those textures separately versus, say, packing them all into a single texture and sampling from that as-needed?


texts: Easiest way to create a 2d game in Java?

texts: I would like to create a 2d game in Java, but tutorials online for game libraries such as LWJGL are usually filled with errors once I compile the project. Most people do not explain very well, and just go on very quickly. Can someone please provide me a couple examples with source code, and somewhere to have a starting point? I used to have trouble with making a GUI and you guys helped me through, hopefully you can do the same again!


texts: LibGDX Box2D Lights - Illuminate background

texts:
I have a box2D world made of tiles. I use a custom DirectionalLight for light up the scene from above (It shines through transparent blocks [eg.: the water] more deeply). The problem is (as expected), as soon as I build a bridge-like thing in the air, I'll get shadows underneath. What I'd like to achieve, is to get light in the places where there aren't any blocks (i.e. neither in the foreground nor in the background).

Should I completely forget the DirectionalLight, or is there any method to easily "post-fix" these shadowed areas?


texts: Drawing thousands of isometric tiles per frame with a high FPS

texts:
This question seems similar to other questions but no other topics I saw helped.
I'm making a game in GML (GameMaker Language).

Regardless of the language/software, this should be a universal topic.

Okay, so I currently barely exceed 60FPS on a game with no code in the tick (step? frame? iteration?) so it should most definitely not be a CPU issue. My computer is fantastic and I can run nearly all (if not, all) games at ultra and high settings. Anyway, my game is isometric and tiles are 32x16.

The terrain data ds_grid (like a 2D array, but can't be jagged) is never changed except when loading other maps. I need the game to be played in a max of 1080p, and higher resolutions won't be implicitly supported.

So, I have a nested for-loop, to loop through a calculated minx/maxx and miny/maxy, basically defining the rectangular area in the terrain data ds_grid that I need to render. However, at the moment, in 1080p, after applying a variable called count to increment every iteration of the nested loop, I have nearly 8000 draw calls every frame, rendering every tile near the view.

Remember, the tiles are both isometric and small, so there are a lot of things needed to be rendered. There are multiple grass tiles to reduce texture repeating. There is also a water tile, and I may add other terrain tiles. So basically, I need a method of rendering tons of tiles (that don't change) with a much higher (preferably at least 300) FPS.

MORE INFO:
in GM, a ds_grid is a data structure that is very similar to a 2D array, where the main differences are that it cannot be jagged (it's similar to a table) and any cell can hold any data type, so I could have strings and real numbers etc. all in the same ds_grid.

My ds_grid contains enumeration values, such as tile.grass or tile.water.

The terrain does not fit within the screen borders, and resolution directly affects view size.


texts:
guys!

I would like to create a map where the player can never reach the end while using the awesome navmesh agent from unity.

Is it achievable? I'm thinking of making a treadmill kind of logic with navmesh but since the environment have to be static, I don't think it's workable is it?


texts: Creating laser redirection (eg. Portal 2 Cubes)?

texts:
Okay, so I asked this question about 2 years ago, and revisiting my project, I'm amazed I still can't think of a solution. I seemingly can write basic adventure game engines from scratch, but Unity's component-based programming stumps me.

So basically I have two cubes, SourceCube and RedirectCube. SourceCube is just a cube that fires a laser (for now a raycast).

A redirect cube is a cube that, when hit by a sourcecube laser, will fire its own laser.

My question is, how can I detect when one redirect cube's laser hits another redirect cube, causing the second redirect cube to fire its own laser (basically like the cubes in Portal 2)?

Below in the image, the blue-faced cube is my source cube. The pink ones are the redirect cubes.

Here's the code for the sourceCube (Unity, C#):

using UnityEngine;
using System.Collections;

public class OriginLaser : MonoBehaviour
{
    public RaycastHit sourceOut;

    void Update()
    {
        SourceShoot();
    }

    void SourceShoot()
    {
        if(Physics.Raycast(transform.position, -transform.forward, out sourceOut, Mathf.Infinity))
        {
            Debug.DrawRay(transform.position, -transform.forward * 20000, Color.red);

        }
    }
}

Pretty self-explanatory. Just draw a raycast.

Here's the code for the redirect Cube:

using UnityEngine;
using System.Collections;

public class RedirecCubetLaser : MonoBehaviour
{

    public RaycastHit redirectHit;
    public OriginLaser originRef;

    void Start()
    {
        originRef = GameObject.FindGameObjectWithTag("Source").GetComponent<OriginLaser>();

    }

    void Update()
    {
        Redirect();
    }

    void Redirect()
    {
        if (originRef.sourceOut.collider.name == this.gameObject.name)
        {
            if(Physics.Raycast(transform.position, -transform.forward, out redirectHit, Mathf.Infinity))
            {
                Debug.DrawRay(transform.position, -transform.forward * 20000, Color.green);

            }
        }
    }
}

And this works for detecting sourceCube rays. My question is, how can I get it to detect rays from another instance of the same object (these cubes will eventually become prefabs)?

Say we have two identical objects, RedirectCube1 and RedirectCube2. If sourceCube's ray activates RedirectCube1, how does RedirectCube1 activate RedirectCube2?


texts: How does an Engine like Source process entities?

texts:
On the Source engine (and it's antecessor, goldsrc, quake's) the game objects are divided in two types, world and entities. The world is the map geometry and the entities are players, particles, sounds, scores, etc (for the Source Engine).

Every entity has a think function, which do all the logic for that entity.

So, if everything that needs to be processed comes from a base class with the think function, the game engine could store everything on a list and, on every frame, loop through it and call that function.

On a first look, this idea is reasonable, but it can take too much resources, if the game has a lot of entities..

So, how does a engine like Source take care (process, update, draw, etc) of the game objects?


texts:
I've a very sipmle Unity scene.

It has two objects in it, which is Sprites, and they both use sipmle black boxes as a textures.

Here's two shaders, one should act as a mask, and second as a object, that should be rendered only in pixels, specified by that mask.

Mask shader:

Shader "Unlit/StencilUnlitShader"
{
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
    Tags { "RenderType"="Opaque"
    "Queue" = "Geometry" }

    Pass
    {
        //AlphaTest Greater 0.5 //Only render pixels whose alpha is greater than AlphaValue.
        Stencil{
        Ref 2
        Comp Never//Never - never pass the stencil test, Always - always pass the stencil test
        Pass Replace //write Ref value into the stencil buufer
        }

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

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

        struct v2f
        {
            float2 uv : TEXCOORD0;
            float4 vertex : SV_POSITION;
        };

        sampler2D _MainTex;
        float4 _MainTex_ST;

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = TRANSFORM_TEX(v.uv, _MainTex);
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            // sample the texture
            fixed4 col = tex2D(_MainTex, i.uv);
            //if (col.a < 0.9) discard; //discard a pixel if it's transparent and don't draw it into a buffer
            return col;
        }
        ENDCG
    }
}
}

Object shader:

Shader "Unlit/GreenUnlitShader"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
        SubShader
    {
        Tags{ "RenderType" = "Opaque"
              "Queue" = "Geometry+5" //to draw after stencil object
    }

        Pass
        {
        //AlphaTest Less 0.5
        Stencil{
        Ref 1
        Comp Less //Always, Less - if ref value is greater then current value in the stencil buffer
        Pass Keep
        }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

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

    struct v2f
    {
        float2 uv : TEXCOORD0;
        float4 vertex : SV_POSITION;
    };

    sampler2D _MainTex;
    float4 _MainTex_ST;

    v2f vert(appdata v)
    {
        v2f o;
        o.vertex = UnityObjectToClipPos(v.vertex);
        o.uv = TRANSFORM_TEX(v.uv, _MainTex);
        return o;
    }

    fixed4 frag(v2f i) : SV_Target
    {
        fixed4 col = tex2D(_MainTex, i.uv);//fixed4(0,1,0.5,0.6);
        //if (col.a < 0.9) discard;
        return col;
    }
ENDCG
    }
    }
}

The problem is, this doesn't seem to work, and object doesn't seems to be rendered at all (why it should in the places where mask have it's pixels)


texts: Should texture regions sizes be power of two?

texts:
Is it advisable for my individual texture regions inside this texture to be power of two, or that won't make any difference?

I've read on several places that it's recommended to use power of two sized textures (e.g. Should I use textures not sized to a power of 2?).


texts: Rotating camera based on player's rotation

texts:
I'm trying to have a camera rotate mirror the player's rotation, however, this isn't happening and the camera isn't rotating at all.  Can anyone explain what I'm doing wrong and how to fix it?

public class PlayerActions:MonoBehaviour{
    Camera mainCamera;
    public Rigidbody player;
    public GameObject playerShot;
    public Transform shotSpawn;
    public Boundary boundary;

    public int speed;
    public int tilt;
    public int bank;
    public float fireRate;
    private float shotDelay;

    void Start(){
        mainCamera = Camera.main;
        player.GetComponent<Rigidbody>();
    }

    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 move = new Vector3(moveHorizontal, moveVertical, 0f);
        player.velocity = move * speed;
        player.position = new Vector3(Mathf.Clamp(player.position.x, boundary.xMin, boundary.xMax), Mathf.Clamp(player.position.y, boundary.yMin, boundary.yMax), 0f);
        transform.rotation = Quaternion.Euler(0f, 0f, player.velocity.x * -bank);
    }

    void Update(){
        if(Input.GetKey("space") && Time.time > shotDelay){
            shotDelay = Time.time + fireRate;
            Instantiate(playerShot, shotSpawn.position, shotSpawn.rotation);
        }
    }
}

As it's working now, the player is rotating, but the camera isn't.

If you notice in the video linked below, the ship is rotating, but if you look at the static asteroid, you'll notice that the camera isn't.
Not Rotating Game View
Not Rotating Editor View

Heirarchy

Inspector


texts: Array with multiple linked objects in Unity

texts:
This might be too primitive, but for my use case, I need to maintain an array in which two attributes are linked to each other... For example - If I want to do Score gathering... Then I need an array which has scores and corresponding player names as each element.

So, when I do Array.Sort(PlayerScorearray) I even need the playername to be sorted in the order so that if I want to know the player with lowest score, I just go for the first element and then go to the corresponding player name.. Is it possible to do it in a simpler way? My mind can't think of a simple way to do this.

Edit : I am using C# for scripts


texts:
I use an angle to set the velocity (or direction if you prefer) of my sprite, however, I want the sprite to be heading in the same angle as I'm moving, rotating according to that angle.

How I set angle and velocity:

angle = (float)Math.atan2(0 - pos.y, 220 - pos.x); //using bottom mid of screen as destination for testing

//in update
pos.x += 200 * Math.cos(angle) * delta;
pos.y += 200 * Math.sin(angle) * delta;
sprite.setPosition(pos.x, pos.y);

//in render
sprite.draw(batch);

is there any way to use this value in LibGdx's "sprite.rotate()" function? I can't do "sprite.rotate(angle)". Can I do this some other way? Can I convert my angle-value somehow to degrees? I'm stuck.

I tried

sprite.rotate((float)Math.toDegrees(angle));

but that gave rly weird results, the following image is moving down and to the right


texts:
So here's the problem- I'm writing my own engine library, and it works fine with stuff like menus and the actual game screen. The thing is, I can't really figure out how to integrate something like an intro or dialogue preceding certain levels into this system.
Let's look at another example- say I have a game-specific engine which gets a Level object and runs it. Engine would have its own collision and physics system, all hard coded. Now, what if at some point in a level, I want the player to enter a mini-game with different rules? How do I morph the Engine class to support these sub-systems without having to deal with their code all the time (as in: if(regular game) ... else if(mini game) ...)?

And what if I want an intro animation at the start of a level, and I want the player to be able to assume control of his character once the animation ends, do I implement the animation into the Engine class itself? Or maybe I need to run another class, CutScene, and when it ends, it calls Engine and starts the level? What if I want to add a dialogue system, where at the start of each level there's a short dialogue and the player can't control his character, and once it ends, he can? Would I then run the dialogue code inside the Engine code?

Maybe these sub-systems should all be scripted? I don't know anything about scripting, is it necessary for this kind of situation?
Any help would be appreciated.


texts: Steamworks Networking with LibGDX / Java

texts:
I have recently found out about Steamworks SDK and after reading through some of the documentation and information from other sources I was left with a few questions.

I found Steamworks because I was interested in how Steam handles multiplayer in games, like co-op games with the lobby creation and all.

This is because of a game I'm developing which is planned to be a 2-player co-op puzzle game.
When it comes to networking, how would I program the game to use Steamworks lobby creation? Would I just program it normally with a client server? Because normally that would require atleast one of the users to forward their ports but would the Steamworks work around that? Or do I implement the Steamworks right away?

This would be cruicial to know since adding networking late in to the development is very difficult.
Thank you in advance, any links or help is much appreciated!
Also, I'm progamming in Java(LibGDX).


texts: How to remove white background from an image using LibGdx?

texts:
I am fairly new to game development.

I am developing an application(Aquarium) for windows which requires me to animate(move) fishes around the screen and user will be able to add new fishes drawn on paper and scanned into the application, I did some research and decided to use LibGDX so when user scans the image coming to the system has White background which needs to be removed I needed to know how to remove that make it transparent in LibGDX.


texts: How do people get around the Carmack's Reverse patent?

texts:
Apparently, Creative has a patent on Carmack's Reverse, and they successfully forced Id to  modify their techniques for the source drop, as well as to include EAX in Doom 3.

But Carmack's Reverse is discussed quite often and apparently it's a good choice for deferred shading, so it's presumably used in a lot of other high-budget productions too.

Even though it's unlikely that Creative would go after smaller companies, I'm wondering how the bigger studios get around this problem. Do they just cross their fingers and hope Creative doesn't troll them, or do they just not use Carmack's Reverse at all?


texts: When are oblique triangles used in game development?

texts:
I'm working on a project that explains how trigonometry is used in video games, and I need to mention oblique triangles.
However, as far as I know, only right triangle diagrams are used in video games to perform calculations such as distance and angle.
Are right triangles always used, or are there some cases where oblique triangles are used, in which the Law of Sines and Law of Cosines are also used?


texts:
I'm having difficulties getting a moveable rectangle to collide with more than one rectangle.

I'm using SFML and it has a handy function called intersects which takes 2 rectangles and returns the intersections. I have a vector full of rectangles which I want my moveable rectangle to collide with. I'm looping through this using the following code (p is the moveble rectangle).

IsCollidingWith returns a bool but also uses SFML's intersects to work out the intersections.

while(unsigned i = 0; i!= testRects.size(); i++){
   if(p.IsCollidingWith(testRects[i]){
        p.Collide(testRects[i]);
   }
}

and the actual Collide() code:

void gameObj::collide( gameObj collidingObject ){

 printf("%f %f\n", this->colliderResult.width, this->colliderResult.height);

if (this->colliderResult.width < this->colliderResult.height) {
    // collided on X
    if (this->getCollider().left < collidingObject.getCollider().left ) {
        this->move( -this->colliderResult.width , 0);
    }else {
        this->move( this->colliderResult.width, 0 );
    }

}

if(this->colliderResult.width > this->colliderResult.height){
    if (this->getCollider().top < collidingObject.getCollider().top ) {
        this->move( 0, -this->colliderResult.height);
    }else {
        this->move( 0, this->colliderResult.height );
    }

}

and the IsCollidingWith() code is:

bool gameObj::isCollidingWith( gameObj testObject ){
if (this->getCollider().intersects( testObject.getCollider(), this->colliderResult )) {
    return true;
}else {
    return false;
}

This works fine when there's only 1 Rect in the scene. However, when there's more than one Rect it causes an issue when working out 2 collisions at once.

Any idea how to deal with this correctly? I have uploaded a video to youtube to show my problem. The console on the far-right shows the width and height of the intersections. You can see on the console that it's trying to calculate 2 collisions at once, I think this is where the problem is being caused.

Finally, the image below seems to illustrate my problem nicely:


texts: How to design enemies pattern in non-bullet-hell shmups in Unity?

texts:
I am making a top down shooter.

Enemies will come in waves and attack in many different patterns (i.e. wave of 10 enemies flying in a elliptic curves, or a huge boss floating and shooting at you, etc.).

I'm thinking of 2 solutions:

Design paths using an animation tool
Hard-code paths

For the first solution, I think it will be faster to create the paths since I will be able to see them in the tool, but is it performant? There will be hundreds of flying patterns in my game.

I've also heard of BulletML, but looks like it's more for bullet-hell shmups, and there's no visual editor to design the patterns easily.

Are there other solutions to design path patterns for non-bullet-hell shmups which I haven't considered?

What are the pros/cons of each solution?


texts: How do I highlight terrain around an object within certain radius?

texts:
In my project, a player is not allowed to place forces in a given radius around enemy defensive forces. I would like to distinguish this area using some sort of highlight.

Second, I want calculate the radius for each enemy when the player placing forces clicks to check whether this player can put it there or not. Is there a more optimized way to do this other than looping through each character?


texts: How to change chance of spawn based on distance?

texts:
I am trying to make a cellular automate cave but want to keep the middle empty.

How should I change the chance based on the distance from the middle?

I don't want to completely deny it just want a small enough chance to keep it almost empty.


texts: Dissolve object starting from the bottom

texts:
I'm currently getting into using the new "Unity Shader Graph"s and have made an OK dissolve shader that looks like this:

My next goal is to move this effect so the object dissolves bottom-up. This is where I'm stuck. I tried blending this effect with another effect that just fades the object from the bottom up but this does not create the effect I am looking for (#1 is the fade effect, #2 is the two shaders blended together):

The end effect should look something like this:

How can I achieve this effect? Answers do not have to be specific to Unity and a good answer should include the thought-process to creating this effect, not just code or pictures of a shader graph.


texts: Rendering detailed martian terrain for an RTS

texts:
I am trying to develop a RTS game that has:

Various planets
Each planet topology could vary between chock full of craters, to smooth hills and mountains planets
In sum each "biome" should be unique-ish (try to reusable textures/objects)

I'd like to achieve an appearance similar to Mars Battle, with its usual terrain with craters and rocks, smoothly transitioning to giant features like this detailed crater:

What I've already know/tried in my tests of terrain:

Unity terrain - it does the job for the small gravel and rocks but for example the finest detail of ridges on the crater edges is not achievable. The amount of mesh detail is not enough, makes blurry.
2D tilesets - I have experimented in the past with 2D tilesets and read some articles about how Starcraft II uses some hacks to give the impression of relief while only being a 2D image, but still this is so seamless!
2D tilesets for terrain, meshes for crater - could be a mix? In that case my doubts are the seamlessless between terrain and crater mesh. And also how can there be constructable buildings inside the crater if is a mesh?

How can I achieve something like this?