texts: Mini Game Platform for PC - similar to Warcraft III Custom Games

texts:
I think it would be fun to make a game for pc that has an online community like Warcraft III (the RTS, not the MMORPG), aka there's lobbies and chat rooms and users can host games to play with eachother. And there's no seriousness, just fun mini games that last on average 30-60 minutes, more or less depending on the game.

I searched google but it's really hard to find anything. Is there anything similar to this idea that's already out there? Or is this a first?

Also, in making this, any recommendations, flaming, or random comments? (yes I know it is hard to make an online game and such, especially since I have no experience with networking. I do have 2-3 years of programming experience, however).

Some more info on what I want to create.

I want it to be easy for users to create games and play with friends. All of us game creators have ideas, and we probably draw them out on paper (graph paper for me). Wouldn't it be amazing if it was a matter of a couple hours to transfer that idea to a fully working game, even if it is in 3d?


texts: How do mipmapping, anti-aliasing and anisotropic filtering contribute to rendering quality?

texts:
To my understanding, mipmaps exist to save on computations and memory when textures are far away. In an ideal world, we wouldn't want them. We'd just use the same high quality textures far away and not care about wasted resources.

But in reality, we need anisotropic filtering to smooth the disconnect between varying LOD mipmaps (or so I think).

However, do images using mipmaps with anisotropic filtering look better than no mipmaps without anisotropic filtering? See here (the first image looks worse than the third even though the first has no mipmaps). Is it because anisotropic filtering has anti-aliasing built in? And if we didn't have mipmaps, but added anti-aliasing, would the resulting image look better?


texts:
I had been repetitively watching this part of the video just trying to understand his point:

  you can optionally use the return value as cell index ... as random
  seed to introduce some variation ...

at the near end of the video he stress that:

  don't use for loop ... anything can be achieved by repeating space ...
  I will make an operator to repeat an interval ... give it additional
  values like the first and the last cell index ... start by -2 and end
  at +2 then you get 5 objects ...

How can we achieve like what he say? Do we use clamp() to do that? Something like:

float a = clamp(pMod1(pos.x,2),start_value, end_value);

It is brilliant that everything he present is just like magic to me.

Update01

I dig deeper into SDF research and reading more codes from shadertoy, and discovered this interesting capsule code:

float sdCapsule( float3 p, float3 a, float3 b, float r ) {
    float3 pa = p - a,
    ba = b - a;
    float h = clamp( dot(pa, ba) / dot(ba , ba), 0.0, 1.0 );
    return length( pa - ba * h ) - r;
}

Basically, length(x)-r will get sphere, for x as the origin of the sphere and r is radius of the sphere. so the sdCapsule to some extend, is a variation of sphere, with the clamp(). That means my speculation might be correct. However, I still not sure what that clamp() do and how to adapt it to my use.


texts: What should I keep in mind when developing a game to be multiplayer?

texts:
I am making 2d game, and it will be a game where players can move on in a 2D world and there will be physics with projectiles and such.

So far, I don't have much, just a tile engine a few other things.

But this game is going to be fully multiplayer, and I've never made a multiplayer game before. Obviously I can't be making multiplayer as I develop the game, I kind of have to make it and then hope it works once I add multiplayer.

So my question is, is there anything I should keep in mind when developing this game to be multiplayer? I'm not asking, how to make it multiplayer, thats a whole other question. I just don't want to have to re-develope everything because I did something wrong that does not work with multiplayer?

Edit: Also, as a side question, do you have any advice on what general order to create the game, and when to add multiplayer?


texts: How much detail should I provide in reference material to potential contract composers?

texts:
I'm not very good with music, so when the time comes I'll need help from a composer for my game. I'm unsure of how to actually work with one.

Despite my lack of musical understanding, I know what I like. I might listen to some music and think "Hey, this kind of music would be awesome to have in the epic chase scene near the end of the game, where our heroes just barely manage to escape!"

When I go to hire a composer to make music for my game, how much detail and reference music should I provide? Should I provide lots of long descriptions of what I'm after, lots of links to music that I think fits the theme? Or should I just let the composer play the silent game and work it out themselves?


texts: What project template to use for an 8bit RPG?

texts: Should I use a 2D or 3D dimension for an 8-bit RPG game in Unity? I have been searching and I haven't found anything on this yet. Can anyone please tell me the better option because sometimes people recommend to do 3D just in case, but I don't want to mess anything up later on.


texts: How to draw portion of a sprite in libGDX

texts:
Let's say i have a sprite like this:

and i want to draw the lower portion of it, only the yellow color..
Initially the sprite has dimensions 10x10, i want it to be drawn 10x3

Do i have to redimension both the sprite and the texture region to mantain proportion between the two?


texts: Turn based multiplayer, Google services or Parse or..

texts:
I have a turn based game on Google play already (paid with around 2000 users and free with around 50k).i am thinking of adding multiplier option to it. I am unable to progress because I don't know which path to take (given its my first multiplier game). I need your help

Like any turn based app, you have the concept of players joining in, rooms, scores and ranking (linking it with fb is preferred)
For my backend server, which option should I go with? Google play game services, Parse, AppWrap.. Etc or simply me use my website server and do the server code?

I am leaning towards Google Game services just because the infrastructure is there and it's free. But I don't find it to provide flexibility and control (such as using nicknames, listing rooms.. Etc)

I just heard about Parse so no experience

Any help or recommendations? Plzzzz need your advice


texts: Dynamically applied texture to GameObject using GUI button

texts:
In a scene I have multiple different GameObjects (almost 30 kinds) with parent child relationships. At run time (by using a GUI button) I want to change the texture of each clicked GameObject. As the user clicks specific GameObjects, a GUI with a multiple texture button will appear. By clicking on the button, that specific texture will be applied.

Is there a smarter way to do this?

Do I need to apply a script to every object?

I have tried to apply a script with some specific code; it's working but not regularly and correctly.  Additionally, I want different texture options for each kind of GameObject.


texts:
I am doing a 2D casual puzzle where the user can drag and drop some pieces into a board. The pieces are 2 or 3 or 4 tiles. Each tile may have text over the sprite.

Target platform: Mobiles and tablets.

I wonder if the right approach is to use 2D sprites or to use UI images for displaying the board, the tiles and the pieces on it.

On one side, doing all the game based on UI elements seem weird.
On the other side, if I do it based on sprites, how do I attach texts on the sprite?

Which approach should I pick?


texts: Unity, Replace or modify camera with own script

texts:
I am making an RTS game which has a slowdown when many units are on screen at once. I have a plan to write my own camera script to speed this up.

Since I have an efficient way to find where units are without the raycast, I want to write scripts to replace the camera and check raycasts against only the few objects that my scripts will identify as in the correct area for that raycast?

Alternatively is is possible to have the camera ignore certain entities on one part of the screen, and then a different set on another part of the screen?

--Edit--
I am very grateful for people helping in anyway, but I wanted to know if this Could be done even if in my case it shouldn't be.


texts: When should I use one over the other? I'm pretty sure I understand the key differences, but I'm not sure which use cases would prefer one over the other. For example, let's say I have objects on the ground in my 3D game and they have UI Images above them with the objects' names. Which method is better? Should I stick to world space for objects which are located in the 3D world and screen space for overlay type stuff?


texts: Which structures to use for maintaining 2D objects on canvas? How to map clicks to objects?

texts:
I need to draw some 2D objects on a canvas. And I need to map the 2D coordinates of clicks to objects.

What is the usual way to maintain a 2D object's size and position (which data structures,  etc.)? What's the effective way to say: this object is at coordinates (x, y)?


texts: Unity 5.3.4: Controlling multiple audio sources at once?

texts: Is there a way to control the max distance of a group of audio sources at once? I want to implement all my sounds, then be able to play with some of the audiosource settings of all of them..


texts: How do .HLSL files work together compared to .FX?

texts:
So I have been slowly reading and working through Frank Luna's D3D11 book which uses the .FX file format which uses effects, techniques and passes which I understand now. However I have read online that the FX framework is no longer supported so I shouldn't use it. How do .HLSL files work? Do techniques, passes and effects still work the same way? Can I still use functions like:

CreateEffectFromMemory();


texts: How can I test DXGI_ERROR_DEVICE_REMOVED error handling?

texts:
My application uses DX11 and it periodically gets a DXGI_ERROR_DEVICE_REMOVED error on startup. It is an infrequent thing (I can go days or weeks without seeing it) but according to the documentation here it should be expected and handled smoothly.

Because it is so infrequent I cannot debug or test this scenario.  I have tried changing video card settings while the app is running, switching users, etc.  I cannot seem to trigger it.  What can I do?


texts: Making a Point Light follow a cube (Unity)

texts:
I'm trying to have a point light positioned directly above a cube follow wherever the cube goes. However, it doesn't move at all. This is my code for the light:

using UnityEngine;
using System.Collections;

public class SpotlightController : MonoBehaviour {

// Use this for initialization
void Start() {

}

void OnGUI(){
    GUI.Label(new Rect(20,50,500,20), "(" + transform.position.x.ToString() + ", " + transform.position.y.ToString() + ", " + transform.position.z + ")");
}

// Update is called once per frame
void Update() {
    GameObject cube = GameObject.Find("Cube");
    float xlocation = cube.transform.position.x;
    float zlocation = cube.transform.position.z;

    transform.TransformPoint(new Vector3(xlocation,transform.position.y, zlocation) * Time.smoothDeltaTime);
    //transform.Translate(new Vector3(xlocation, 0, zlocation));
}
}


texts: How portable are OpenGL versions, really?

texts:
If I write a game engine that uses OpenGL 1.5 (not assuming what else I do), is it portable now and is it still portable five years from now or are/will support for OpenGL by hardware and drivers (be) exclusive to their (much more farther along) target OpenGL versions?

Lately I've been looking at a lot of answers on this website that direct users to divert their work towards the most recent OpenGL versions, citing hardware surveys of DirectX support and only recommending earlier versions as a last, final resort (as if to imply there is something wrong with them that makes all usage of them invalid or pointless).

If I only have computers that can provide OpenGL <=1.5 or <=2.1 contexts should I just give up game programming if I can't afford a new computer with hardware and drivers for 3.x and 4.x?  Or should I finish my game engine the way I intended to?

Will by the time I get a 4.x supporting setup will there be new versions and a lack of backwards compatibility that trash all usage of 4.x?  Will 4.x ever dominate over earlier versions support wise before a new major version is realized and released?


texts: How to split a 2D sprite tile set into individual sprites?

texts:
I see a lot of sprite catalogs for games provided as single PNG image, like the one below.

I'm interested if I have to manually create tiles from that, or if there's some program that can split it into various tile combinations for me? For example, given the tile combination below, I will have to create a flat grass surface, and 8 other combinations with various edges. Is there something that can automate this task?


texts: Why is there a huge update-delay in my client/server code?

texts:
I'm working on my Java game with Libgdx and having trouble with the network code. I can create a server, make multiple clients connect to it, but there is a huge delay between the player's input and the movement.

This is basically how it should work:

SERVER:     (Launch and listen to connection.)
CLIENT: I want to connect
SERVER:     OK, here is the map and all other data
CLIENT: I pressed "D"
SERVER:     OK, I move this player, here is your position
CLIENT: I received my position

On the 2 last steps, when I pressed an input, the server gets it correctly and updates the position and immediately sends the position to the player, but here is my problem:

Server log (the numbers are X- and Y-coordinates):

Sat Sep 20 18:49:16 CEST 2014 : Send 2356.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2358.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2360.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2362.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2364.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2366.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2368.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2370.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2372.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2374.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2376.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2378.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2380.0 1376.0

Client log:

Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0

As you can see, the player receives the data at the wrong moment. Here is when the client start to receive

Sat Sep 20 18:49:18 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2338.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2340.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2342.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2344.0 1376.0

As you can see, there is almost a 2 seconds of delay (something like 1.6 / 1.7s).

This is how I send/receive data:

Sending:

synchronized(this.gestionPlayers) {
   for(GestionPlayer gp : this.gestionPlayers) {
        if(this.serializablePlayer.size() > 0)
            gp.sendPlayer(this.serializablePlayer);
    }
}

sendPlayer function:

try {
    this.objectOut.writeObject(sp);
    this.objectOut.reset();
} catch (IOException e) {
    this.actif = false;
    e.printStackTrace();
}

Receiving:

Vector<SerializablePlayer> p =
    (Vector<SerializablePlayer>) this.objIn.readObject();
this.map.addNewPlayers(p);
this.map.multiplayerRender();

SerializablePlayer contains the player's ID and coordinates.

If you need more information, just ask. This is the last step in my multiplayer game and I'd be happy if you could help me! :)


texts: So I have a 16x16 sprite. I would like to make each pixel on the sprite to have a border/outline so you can distinguish each pixel from another, like shown in the picture below (ignore the colored boxes). How would I do so? Please note, I will be coloring those pixels, so those borders should be gone when colored


texts:
I ended up coming up with having states within game states. For example:

States

splash
menu
tracks
garage
loading
play

What bothers me is that I now have states within the play state to handle it based on the vehicle states:

vehicle_flipped
vehicle_damaged
vehicle_out_of_fuel

Which just doesn't sound right. I was thinking of merging the play state's states with the game states, but then it feels like I am hacking when I juggle the box2d world through the game state manager to another game state.

Any ideas on how to approach this dilemma?


texts:
Forgive me for my English. I am trying to create a 4x4 matrix in vertex shader, but it is not initialized correctly. Why is this happening?
Vertex shader:

struct LogicBufferPosition
{
    matrix Pos;
};

struct LogicBufferBool
{
    bool flag;
};

StructuredBuffer<LogicBufferPosition> arrayPositions: register(t0);
StructuredBuffer<LogicBufferBool> arrayBools: register(t1);

cbuffer ConstantBufferVS: register(b0)
{
    matrix World;
    matrix View;
    matrix Perspective;
};

struct VS_INPUT
{
    float3 Pos: POSITION;
    float3 TexCoord: TEXCOORD;
    float3 Normal: NORMAL;
};

struct GS_INPUT
{
    float4 Pos: SV_POSITION;
    float3 TexCoord: TEXCOORD0;
    float3 Normal: TEXCOORD1;
    bool visible: VISIBLE_FLAG; // отрисовывать ли примитив?
};

GS_INPUT main(VS_INPUT input, uint id: SV_InstanceID)
{
    GS_INPUT _out = (GS_INPUT)0;
    if(arrayBools[id].flag == false)
    {
        _out.visible = arrayBools[id].flag;
        return _out;
    }

    float4x4 translateCenter =
    {
    1.f,0.f,0.f,-input.Pos.x,
    0.f,1.f,0.f,-input.Pos.y,
    0.f,0.f,1.f,-input.Pos.z,
    0.f,0.f,0.f,1.f,
    };

    float4x4 translateCenterInverse =
    {
    1,0,0,input.Pos.x,
    0,1,0,input.Pos.x,
    0,0,1,input.Pos.x,
    0,0,0,1
    };

    _out.Pos = mul(float4(input.Pos, 1), World);
    _out.Pos = mul(_out.Pos, translateCenter);
    _out.Pos = mul(_out.Pos, arrayPositions[id].Pos);
    _out.Pos = mul(_out.Pos, translateCenterInverse);

    _out.Pos = mul(_out.Pos, View);
    _out.Pos = mul(_out.Pos, Perspective);
    _out.TexCoord = input.TexCoord;
    _out.Normal = input.Normal;
    _out.visible = arrayBools[id].flag;
    return _out;
}


texts: What is the difference between transform.translate and rigidbody.velocity?

texts: I've been tying to understand what the difference between these two methods of moving a rigid body are.  Both seem to move the object at a constant rate and both operate on a RigidBody.  So what's the difference between the two and when should one be used over the other?


texts:
I would like to compute short distance from reference point in 2d grid. To expose:

0, 0: not penetrable
0, 1: not penetrable
...
1, 1: penetrable
...

I search an algorithm who return:

1, 1: 1
2, 1: 1
3, 1: 1
1, 2: 1
2, 2: 0
3, 2: 1
...
1, 6: 4
3, 6: 4

for 2, 2 reference point, 4 as maximum distance in exemple grid. What algorithm can to this (with good perf) ?


texts:
I'm currently stuck on something that just seems extremely odd. I'm creating a game with kinect, and when the player performs an action I want to place a texture onto the screen where their hand is.

I currently have that code implemented. I have something like:

var myVector = Skeleton[JointType.RightHand].Position;

When I get the vector coordinates I store them in an array and that allows me to reference it later if/when I need to. That is the HitVectors array.

The numbers that are recorded into the array are the actual coordinates of the [RightHand] in relation to it's pixel coords on the screen. So for instance your hand is at 100X and 400Y. the array gets a new Vector2(100f, 400f), and so on...

public override void Draw(GameTime gameTime)
{
        // This game has a blue background. Why? Because!
        ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                           Color.CornflowerBlue, 0, 0);

        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

        spriteBatch.Begin();

        spriteBatch.Draw(targetTexture, hostileOne.CollisionBox, Color.White);

        if (hostileOne != null && hostileOne.HitVectors.Count > 0)
        {
            foreach (var pos in hostileOne.HitVectors)
            {
                //trying to get the textures to not draw in a diagonal line
                //spriteBatch.Draw(impactTexture, pos, Color.White);
                spriteBatch.Draw(impactTexture, new Rectangle((int)(pos.X), (int)(pos.Y), 256, 256), Color.White);
            }
        }

        spriteBatch.End();
}

but the texture isn't drawn to those coordinates on the screen. Instead they are essentially only drawing on a diagonal line, at a 45 degree angle. It seems like the oddest thing to me. I've double checked to make sure that the position coords being passed into the sprite batch are correct, and they are. I've checked to make sure that the coordinates of the hand joint that i'm tracking is at the correct X and Y coordinates when I record its position. So to me, everything seems good until the spritebatch.Draw() method is executed.

For extra info, my texture is a 256x256 png file, the spriteBatch being used is from the GameStateManagement example. It's in the ScreenManager class.

photo of issue: http://i1366.photobucket.com/albums/r770/csmhowitzer/debugdiag_zps4239d261.png

How I convert my Kinect joint position in 3D space to 2D:

protected Vector2 CalculatePointPosition(SkeletonPoint point)
    {
        var pointx = point.X;
        var pointy = point.Y;
        var pointz = point.Z;
        var pointnormx = pointx / pointz;
        var pointnormy = pointx / pointz;

        return new Vector2((pointnormx + 0.5f) * (int)screenSize.X, (pointnormy + 0.5f) * (int)screenSize.Y);
    }

If you need any more info let me know.

Thanks in advance everyone


texts:
I'm trying to make my character bone "chest" rotate smoothly when face enemy and get back to his stand. Can anyone help me with this ?

public Transform Target;
public Vector3 Offset;

Animator anim;
Transform chest;

public float rotation_speed;
public bool aim_at_traget = false;

void Start()
{
    anim = GetComponent<Animator>();
    chest = anim.GetBoneTransform(HumanBodyBones.Chest);
}

void LateUpdate()
{
    if (aim_at_traget == true) {
    // smooth rotation to face target
    chest.LookAt(Target.transform.position);
    chest.rotation = chest.rotation * Quaternion.Euler(Offset);
    }
    else {
        // get back to you stand smoothly
    }
}


texts: Is a 3D renderer with 1000 FPS possible?

texts:
Okay, for my phD Thesis, I need to make a simple 3D game, like towers of hanoi or whatever but there is a condition:
I need it to have high FPS, as in, the highest FPS achievable, atleast a 1000FPS. I need to have a high FPS to measure reaction times. We achieve this with 1ms monitors BUT on the programming front, here is the problem,

I'm confused if I should code an entire specially made engine with only the features I need (using Vulkan), and if I did would it be faster than already available engines like Unity or Unreal? Would it be worth the time and effort or can these engines be customised themselves and is that easier than doing it from scratch?

Or is it only achievable with specialized hardware? So I'd be better of using an available engine and going hard on the hardware?


texts: Is the GraphicsDevice.Clear call in XNA necessary in 3D?

texts:
It's a touch embarrassing to ask I think, but I've just never paid it any attention before and used it as I've seen in tutorials or the like in the past I believe.

Is there a need to use GraphicsDevice.Clear?
If you don't use a skybox or similar, how do you change the "void" color from purple to something else?

I'm not seeing a way to change the backcolor or w/e you'd call it in 3D. I also can comment out the GraphicsDevice.Clear call I've always seemed to use and nothing seems to change.

Thanks!

Edit: With the code below, I still get a purple background:

    //Part of Game1.cs
    protected override void Draw(GameTime gameTime) {
        frameRate++;
        Map.ResortChunkPriority(Player);
        //GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.White, 1f, 0);
        Map.Render(GraphicsDevice, clsResources.eTerrain, Player);
        base.Draw(gameTime);
    }

    //Map.Render call
    public void Render(GraphicsDevice device, Effect effect, clsEntity Player) {
        effect.CurrentTechnique = effect.Techniques["MainTech"];
        effect.Parameters["VP"].SetValue(clsCamera.viewMatrix * clsResources.projectionMatrix);

        device.Indices = clsResources.indexBuffer;

        for (int i = 0; i < RenderQueue.Count; i++) {
            //if (RenderQueue[i].fDist > 10) continue;
            RenderQueue[i].Render(device, effect, Player.ChunkPosition);
        }
    }

    //RenderQueue's Render call
    public void Render(GraphicsDevice device, Effect effect, strVector2 CurrentChunk) {
        if (iGenState != 4) return;
        effect.Parameters["xOffset"].SetValue(CubeOffset.X);// + ChunkPos.X);
        effect.Parameters["zOffset"].SetValue(CubeOffset.Z);// + ChunkPos.Z);

        for (int i = 0; i < effect.CurrentTechnique.Passes.Count; i++) {
            effect.CurrentTechnique.Passes[i].Apply();
            FaceStrips[0].Render(device, effect); FaceStrips[1].Render(device, effect);
            if (CurrentChunk.Z >= ChunkPos.Z) FaceStrips[2].Render(device, effect);
            if (CurrentChunk.Z <= ChunkPos.Z) FaceStrips[3].Render(device, effect);
            if (CurrentChunk.X <= ChunkPos.X) FaceStrips[4].Render(device, effect);
            if (CurrentChunk.X >= ChunkPos.X) FaceStrips[5].Render(device, effect);
        }
    }

    //FaceStrip's Render call
    public void Render(GraphicsDevice device, Effect effect) {
        if (iVertCounter == 0) return;

        for (int j = 0; j < geometryBuffer.Length; j++) {
            device.SetVertexBuffer(geometryBuffer[j]);
            device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, geometryBuffer[j].VertexCount, 0, geometryBuffer[j].VertexCount / 2);
        }
    }


texts: In Unity, why does DrawProceduralNow work in OnRenderObject but DrawProcedural does not?

texts:
In Unity, if I call DrawProcedural (or one of its variants) from Update() it works fine, but if I make the exact same call from OnRenderObject() it draws nothing.  (It also doesn't work from OnPreRender or OnPostRender).
HOWEVER, DrawProceduralNow() works fine from all of these functions.
Why is that so? Is it documented somewhere? What can I do to make DrawProcedural and variants work in OnRenderObject? What is different about DrawProceduralNow that makes it work?  (Yes, I have tried using material.SetPass(0) in the DrawProcedural version and it still renders nothing.
I understand that the OnRender functions are called later in the frame and some graphics state is different at that point, but it seems like DrawProcedural is exactly the kind of thing we should be doing in OnRenderObject. I feel like there is some fundamental thing about the Unity rendering pipeline that I am misunderstanding that would clarify all this. (Tested in 2019 LTS and 2020.2.3)
For example:
C#
public class TestRender : MonoBehaviour {

  public Material material ;
  private ComputeBuffer vertexBuffer;
  private GraphicsBuffer indexBuffer;
  private ComputeBuffer paramsBuffer;

  private Bounds _bounds;

  void Start () {
    material = new Material(material);

    // Copy geometry from MeshFilter (you can just use a cube for testing)
    Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
    vertexBuffer = new ComputeBuffer(mesh.vertices.Length, Marshal.SizeOf<Vector3>());
    indexBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Index, mesh.triangles.Length, Marshal.SizeOf<int>());

    vertexBuffer.SetData(mesh.vertices);
    indexBuffer.SetData(mesh.triangles);

    paramsBuffer = new ComputeBuffer(5, sizeof(int), ComputeBufferType.IndirectArguments);
    paramsBuffer.SetData(new int[] { mesh.triangles.Length, 1, 0, 0, 0 });

    material.SetBuffer("_VertexBuffer", vertexBuffer);

    _bounds = new Bounds(transform.position, new Vector3(5, 5, 5));
  }

  private void Update() {
    // This works!
    Graphics.DrawProcedural(material, _bounds, MeshTopology.Triangles, indexBuffer, indexBuffer.count);

    // So does this!
    material.SetPass(0);
    Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count);
  }

  private void OnRenderObject() {
    // This does NOT work
    Graphics.DrawProcedural(material, _bounds, MeshTopology.Triangles, indexBuffer, indexBuffer.count);

    // But this does!
    material.SetPass(0);
    Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count);
  }
}

Simple shader:
Shader "Test Render" {
     SubShader {

         Pass {
         CGPROGRAM
         #include "UnityCG.cginc"
         #pragma target 4.5
         #pragma vertex vertex_shader
         #pragma fragment fragment_shader

         StructuredBuffer<float3> _VertexBuffer;

         struct v2f {
             float4 pos : SV_POSITION;
         };

         v2f vertex_shader (uint id : SV_VertexID, uint inst : SV_InstanceID)
         {
             v2f o;
             float4 vertex_position =  float4(_VertexBuffer[id],1.0f);
             o.pos = UnityObjectToClipPos(vertex_position);
             return o;
         }

         fixed4 fragment_shader (v2f i) : SV_Target
         {
            fixed4 final = fixed4(0, 0, 1, 1);
            return final;
         }

         ENDCG
     }
     }
}


texts: In OpenGL Shader, Why adding color change vertex position?

texts:
I have the following vertex shader:

#version 120

attribute vec4 position;
attribute vec4 acolor;

varying vec4 theColor;

void main(){
    gl_Position = position;
    //theColor = acolor;  //[1]
    theColor = vec4(1.0,0.0,0.0,1.0); //[2]
}

When I use line [1], the color is transmitted rigth to the fragment shader, but when I change the color to the attribute acolor (using the line [2]) the positions of the triangles appear wrong. From the data of the main program, it seems to me like the positions get the color values.

I put two images, 1 with the rigth vertex positions and  2 with the wrong vertex positions.

UPDATE: render code on Github


texts: Unity Rotate Object Around Local X Axis , then Local Y Axis, then Local Z Axis (like a turtle)

texts:
I am having trouble getting my unity gameobject to rotate in the manner I would like.

I would like my gameobject to act kind of  like a turtle from a drawing program, where I could input a Vector3 like (10, 25, -5)  and then it would rotate around its x axis by 10 degrees.  Then rotate around it's Y axis by 25 degrees, and then rotate around it's z axis by -5 degrees.

Here's a picture example: (rotations not exact)

The problem is that the axes (the green, blue, and red gizmos you see when you have an object selected) change direction as the "turtle" goes through the Vector3.

It seems like transform.Rotate(new Vector3(10,25,-5), Space.Self) should be what I'm looking for.
But it doesn't give me the result I would like! It still seems to rotate around it's start up, right, and forward vectors.

public Vector3 rotation;

Quaternion zero = new Quaternion(0,0,0,1)

void Update()
{
    transform.rotation = zero;
    transform.Rotate(rotation, Space.Self);
}

I have also tried doing some things with Quaternions to get the desired result, but I can't figure out exactly what is need. If anyone has any advise it would be greatly appreciated!


texts: How can I fill a Color[] from a Texture2D given a Rectangle in SharpDX?

texts:
I used to fill a Color[] using XNA's

Texture2D.GetData<T>(int, Rectangle?, T[], int, int)

method, but there doesn't seem to be an equivalent overload on SharpDX's Texture2D. Anyone know how I can get this same functionality with SharpDX?

EDIT

How can I fill a Color[] from a SharpDX.Toolkit.Graphics.Texture2D given a Rectangle in SharpDX?


texts: Most efficient way to determine if an entity is in a player's field of vision?

texts:
So I'm creating a real time multiplayer game.. and I only want entity data to be sent to a user if it's in their field of vision + a little more. (It's third person so it would be a giant box around a person)

What would be the most efficient way to do this? The only thing I could think of is have a giant box around the player and then loop through every entity to see if it's in the box and if it is send the data to the player, but doing that for a lot of players would be way too extensive on the server side.

So what's a workaround to this?


texts:
I've read this artical on tilemap optimization https://www.scirra.com/blog/ashley/3/tech-blog-tilemap-tidbits and wondering what algorithm is used to achieve something like this.

I'm wondering how they convert an array of tiles into simplified rectangles that use the same texture. To optimize rendering


texts: How to write depth texture and read values from it

texts:
I am new in Unity and specializing in another field. But now I have to rapidly study it for a new project. I will be very thankful if anyone explain me how to read values of the depth buffer.
I wrote a shader, which creates depth image:
Shader "Custom/MyDepthShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}

    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert // compile function vert as vertex shader
            #pragma fragment frag // compile function frag as fragment shader

            #include "UnityCG.cginc"

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

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

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

            sampler2D _MainTex;
            sampler2D _CameraDepthTexture;

            fixed4 frag (v2f i) : SV_Target
            {
                float depth = tex2D(_CameraDepthTexture, i.uv).r;
                depth = Linear01Depth(depth);
                depth = depth * _ProjectionParams.z;
                return depth;
            }
            ENDCG
        }
    }
}

Now I need to get depth information into a texture and save float values of this texture to for example txt  file for further processing.
I didn't found yet answer to this question after two days of googling and reading guides.
For testing this shader I am using OnImageRender(RT src, RT dst, material).


texts: How to get the center of a rotated rectangle regardless of point of rotation

texts:
I need help working out the centre coordinate of a rotated rectangle regardless of the point of rotation (i.e. the rectangle doesn't rotate around its center). I do not know the coordinates of the corners, so it's not a simple case of dividing those.

It's easier to show than tell, so here's example 1:

http://gametest.mobi/rotate/index.php?f=point1.js&d=tests

Click to start/stop the rotation.

In this example I've got my sprite with the rotation point set to the bottom-right corner of it. If you click you'll see it rotate around that. I need to find a way to work out the coordinates of the center of the rectangle (represented by the middle red cross-hairs.)

Here is another example, this one is set to rotate at 0.3 x 0.8 into the rectangle:

http://gametest.mobi/rotate/index.php?f=point3.js&d=tests

You can see I added the circle into each demo, this is positioned on the sprites x/y coordinate and the radius was calculated from the distance of the center of the rectangle to the rotation origin.

I can visually see the correlation between the point of rotation and the circle, and I can see it tracks the centre of the rectangle beautifully on the circles perimeter! But I'm falling at the last hurdle in trying to calculate the actual value, so desperately need a fresh set of eyes on it please.


texts: Drawing a line from a random coordinate through a given point

texts:
When the mouse button is clicked, I want to draw a line from (0, random) to (640, y) which goes through the click position.

How would I calculate the y coordinate of the end of the line?


texts: How can I rotate childrens nodes with parent node in cocos2dx?

texts:
Consider the following code...

cocos2d::Node* parent = cocos2d::Node::create();
cocos2d::Node* child = cocos2d::Node::create();
parent->addChild(child);
parent->rotate(-90.0f); // But its not affecting the child position

When I am rotating the parent node by an angle, It's not affecting the child node position. How can I get it right? Please help. Thanks.


texts:
I have some prefabs and if I change a value of a script on them - as to be expected - it turns bold meaning if I apply, that value will be input for all of my prefabs. The problem is, I wish to have a value changed only on the instance and then change something else and apply only the latter.
How can I do that? So how can I specify which values are "applyable" and which are not?


texts: IDE cannot find CoreMinimal.h, Unreal Engine 4 course

texts:
I'm following this tutorial on Udemy about learning the basics of Unreal Engine as I start up my CS degree, and I've reached a problem where CoreMinimal.h cannot be found.

This solution was proposed in the Q&A community, however I still could not quite understand it! I'm still learning and would love some help ;)

Here is my code!

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "ShipController.generated.h"

UCLASS()
class SPACESHOOTER_API AShipController : public APawn
{
    GENERATED_BODY()

public:
    // Sets default values for this pawn's properties
    AShipController();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public:
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    // Called to bind functionality to input
    virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};


texts: libGDX new TextureAtlas(filename) and new Texture(filename) drawing stale image data

texts:
I'm trying to draw an image using libgdx but no matter what I do, libgdx seems to insist on drawing a portion of an image I had loaded and used in an earlier game screen.

In my current game screen (class implements Screen), I have tried loading the image using both an atlas and loading it via the Texture class.  However, when I draw the image in my render method, portions of an image that I had loaded previously are being displayed instead.  Not the image that I am passing to the draw method!

I have tried both loading the image using a Texture Atlas and directly:

private TextureAtlas deckAtlas;
private TextureRegion aceHearts;
// In class constructor
deckAtlas = new TextureAtlas("deck.atlas");
aceHearts = deckAtlas.findRegion("ace-heart");

and:

Texture texture = new Texture("deck.png");
sprite = new Sprite(texture, 72, 0, 72, 100);

Depending on the method used above, I try to display by either:

game.batch.begin();
game.batch.draw(aceHearts, 100, 100);
game.batch.end();

Or:

game.batch.begin();
sprite.draw(game.batch);
game.batch.end();

where game is an instance of a class that extends Game and batch was initialized in that class's create method.

To start from the beginning, in my class that extends Game I call

setScreen(new MainMenu(this));

In Main Menu Screen, I load a skin using

skin = new Skin(Gdx.files.internal("uiskin.json"));

and create a bunch of Scene.2d UI widgets with that skin (the packed image that's loaded by the skin is contributing the image that is being drawn on my next screen when I don't want it to).  Finally, I create the Screen in which I am having the above problems using

game.setScreen(new TableGame(game));

So to summarize, I am loading an image in a class that implements Screen, but that image never gets drawn to the screen.  Instead, an image that I had used in the previous screen is being displayed instead.  Any ideas why?

Thanks for any help.

I am using libGDX 1.3.1 (I think).


texts: Scrolling background after firing projectile

texts:
I have a projectile which I fire using the mouse coords as the direction vector which I scale with a velocity vector and add a gravity vector to complete this simple simulation.

I want to scroll the background in some elegant way, so that I can keep the projectile centred in the red (viewport) whilst following it until I can no longer centre it.

Edit:

When the projectile starts it will be at the left edge so I cannot centre here as there's no room outside the scene, same if the projectile gets to the end of my scene.

How is this situation usually solved?


texts: How to refresh allegro textprintf_centre_ex text upon keypress?

texts:
I'm trying to print the coordinates of a drawn square upon movement. The problem is that the x value doesn't get refreshed on screen.

This is the code I have:

#include <allegro.h>

BITMAP *buffer;

void update_screen(void)
{
    blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); // blit the buffer to the screen
}

int init_double_buffering()
{
    // create the memory buffer
    buffer = create_bitmap(SCREEN_W, SCREEN_H);

    if(!buffer)
        return FALSE;

    return TRUE;
}

int main()
{
    int x, y;

    // install allegro, set graphics mode, etc
    allegro_init();
    install_keyboard();

    set_color_depth(32);
    if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640,480, 0,0))
    {
        allegro_message("Unable to set graphics mode.\n");
        return 1;
    }

    // initialize page flipping
    if (!init_double_buffering())
    {
        set_gfx_mode(GFX_TEXT,0,0,0,0);
        allegro_message("Unable to initialize page flipping.\n");
        return 1;
    }

    // default coordinates for the rectangle
    x = SCREEN_W / 2 - 5;
    y = SCREEN_H / 2 - 5;

    // main game loop
    while (!key[KEY_ESC])
    {
        // game logic
        if (key[KEY_LEFT] && x) --x;
        if (key[KEY_RIGHT] && x < SCREEN_W-10) ++x;
        if (key[KEY_UP] && y) --y;
        if (key[KEY_DOWN] && y < SCREEN_H-10) ++y;

        // you draw everything to buffer
        clear(buffer);
        rect(buffer, x,y, x+9,y+9, makecol(255,255,255));
        textprintf_centre_ex(screen, font, SCREEN_W / 2, SCREEN_H/2,
               makecol(255, 255, 255), -1,
               "X value is %d!",
               x);

        // show the offscreen page
        update_screen();
    }

    return 0;
}
END_OF_MAIN()


texts: Unity Editor Script to instantiate a prefab

texts:
I want to instantiate a prefab within the context menu (Components). I got the code to create the entry in the context menu, but I can't figure out how to place my prefab in the scene. My current code is somehow like this :

using UnityEngine;
using UnityEditor;
using System.Collections;

public static class MenuItemGameobject {

    [MenuItem("GameObject/Create RedBlue GameObject", false, 12)]
    static void Init()
    {
        Debug.Log("here");
        //new GameObject("RedBlue GameObject"); // This adds an empty GO
        //new GameObject((GameObject.Find("UIPlane"))); //This duplicates the GO if it is already in the scene
        //PrefabUtility.InstantiatePrefab(); //This is the method which I guess is needed, but I don't know how to get the GO parameter
    }
}

So again, I want to add my prefab exactly like you add a cube within the context menu.

Edit : This is how a public variable looks like in the inspector :


texts:
I want my character to move smooth not instant stopping etc. I want it to decrease velocity slower not instant. I tried with keystates but that doesn't work for 2 keys at once. I tried using key.keysym.sym in switch to set bools: left, right, up, down if key is held but that does not work too when 2 keys are held.
Now I am using this

void CharProp::handleEvent(SDL_Event e)
{
    if (e.type == SDL_KEYDOWN && e.key.repeat == 0)
    {
        switch (e.key.keysym.sym)
        {
        //case SDLK_w:
        case SDLK_UP:
            cVelY -= CharVel;
            break;
        //case SDLK_s:
        case SDLK_DOWN:
            cVelY += CharVel;
            break;
        //case SDLK_a:
        case SDLK_LEFT:
            cVelX -= CharVel;
            break;
        //case SDLK_d:
        case SDLK_RIGHT:
            cVelX += CharVel;
            break;
        }
    }
    else if (e.type == SDL_KEYUP && e.key.repeat == 0)
    {
        switch (e.key.keysym.sym)
        {
            //case SDLK_w:
        case SDLK_UP:

            cVelY = 0;
            break;
            //case SDLK_s:
        case SDLK_DOWN:

            cVelY = 0;
            break;
            //case SDLK_a:
        case SDLK_LEFT:

            cVelX = 0;
            break;
            //case SDLK_d:
        case SDLK_RIGHT:

            cVelX = 0;
            break;
        }
    }
}

This works with multiple keys but I cannot figure out how to make increasing/decreasing velocity. Do you have any tips how to make it using SDL2?

EDIT: Code for decelerating looks like this

if (!accelerationX)
{
    if (cVelX > 0)cVelX -= 0.5;
    if (cVelX < 0)cVelX += 0.5;
}

Now when character is decelerating it can move through walls because I am subtracting 0.5. I want it to decelerate slow so I don't know what to do( If I changed it to subtract 1 it would work good)Any ideas how to do it?


texts: Better way to generate enemies of different sub-classes

texts:
So lets pretend I have an enemy class that has some generic implementation and inheriting from it I have all the specific enemies of my game.  There are points in my code that I need to check whether an enemy is a specific type, but in Java I have found no easier way than this monstrosity...

//Must be a better way to do this
if ( enemy.class.isAssignableFrom(Ninja.class) ) { ... }

My partner on the project saw these and changed them to use an enum system instead

public class Ninja extends Enemy {
    //EnemyType is an enum containing all our enemy types
    public EnemyType = EnemyTypes.NINJA;
}

if (enemy.EnemyType = EnemyTypes.NINJA) { ... }

I also have found no way to generate enemies on varying probabilities besides this

for (EnemyTypes types : enemyTypes) {
    if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) {
        enemy = createEnemy(types.getEnemyType());
        break;
    }
}

private static Enemy createEnemy(EnemyType type) {
    switch (type) {
        case NINJA:
            return new Ninja(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
        case GORILLA:
            return new Gorilla(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
        case TREX:
            return new TRex(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
     //etc
    }
return null
}

I know java is a little weak at dynamic object creation, but is there a better way to implement this in a way such like this

for (EnemyTypes types : enemyTypes) {
    if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) {
        //Change enemyTypes to hold the classes of the enemies I can spawn
        enemy = types.getEnemyType().class.newInstance()
        break;
    }
}

Is the above possible?  How would I declare enemyTypes to hold the classes if so?  Everything I have tried so far as generated compile errors and general frustration, but I figured I might ask here before I completely give up to the huge mass that is the createEveryEnemy() method.  All the enemies do inherit from the Enemy class (which is what the enemy variable is declared as).  Also is there a better way to check which type a particular enemy that is shorter than enemy.class.isAssignableFrom(Ninja.class)?

I'd like to ditch the enums entirely if possible, since they seem repetitive when the class name itself holds that information.


texts: How can I fix glitchy Collision on my 2D game?

texts:
Update: I fixed the Negative axis glitch but the Invisible wall glitch still exists
I have made a 2D game in Java and I rewrote collision as I added chunks.
I have been having problems with the collision detection function, in the negative x-axis coordinates you fall through the world, and in the positive X-axis you sometimes hit into an invisible wall when there are no blocks next to you in that position.
I have tried altering all the numbers until it worked but the problems still happen
Here is the collision function (True = Yes, they are colliding with a Block | False = They are not colliding):
public boolean isCollidingWithBlock(final Point2D.Double pt1, final Point2D.Double pt2) {
        for(int i=0;i<Level.Chunks.size();i++) {
            if (Math.floor((x)/(Level.chunkX*Tile.tileSize)) == Level.Chunks.get(i).chunkNumber) {
                int chunkN = Level.Chunks.get(i).chunkNumber;
                Point2D.Double chunkpoint = pt1;
                if (chunkpoint.x >= 0) {
                    chunkpoint.x = chunkpoint.x%(Level.chunkX*Tile.tileSize);
                } else {
                    chunkpoint.x = (chunkpoint.x%(Level.chunkX*Tile.tileSize))+((Level.chunkX*Tile.tileSize)*1);
                }
                Point2D.Double chunkpoint2 = pt2;
                if (chunkpoint2.x >= 0) {
                    chunkpoint2.x = chunkpoint2.x%(Level.chunkX*Tile.tileSize);
                } else {
                    chunkpoint2.x = (chunkpoint2.x%(Level.chunkX*Tile.tileSize))+((Level.chunkX*Tile.tileSize)*1);
                }

                for (int x = (int)((this.x) / Tile.tileSize); x < (int)((this.x) / Tile.tileSize + 3.0); ++x) {
                    for (int y = (int)(this.y / Tile.tileSize); y < (int)(this.y / Tile.tileSize + 3.0); ++y) {
                        int chunkXPos = 0;
                        if (x >= 0) {
                            chunkXPos = (x%(Level.chunkX));
                        } else {
                            chunkXPos = (x%(Level.chunkX))+((Level.chunkX)*1);
                        }
                        if (chunkXPos >= 0 && y >= 0 && chunkXPos < Level.Chunks.get(i).blockData.length && y < Level.Chunks.get(i).blockData[0].length && Level.Chunks.get(i).blockData[chunkXPos][y].id != Tile.air && Level.Chunks.get(i).blockData[chunkXPos][y].id != Tile.water && (Level.Chunks.get(i).blockData[chunkXPos][y].contains(chunkpoint) || Level.Chunks.get(i).blockData[chunkXPos][y].contains(chunkpoint2))) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }


texts: How would intensive AI pathing be done server-side in an MMORPG?

texts:
Take WoW or Runescape for an example. You have an incredibly large map, filled with cities and forests, each filled with people and monsters.

Monsters roam around an area at random that is 25x25 tiles big (ambiguous). This is done server-side, so every player than comes across this area sees the same location of the same monster, and when a player attacks/kills that monster; other players see it too.

How is this calculated without being a massively intensive task? If you have 500 different types of monsters, all of which have 5 maximum spawned, you'll be calculating 2500 different paths continuously.


texts:
Is there an isometric 2d game that doesn't use tilemapping?

I want to do this in tilemap but the client doesn't want to use it (since it's easier to design maps without using tiles).

I've tried to research for some time and everything's done using tilemapping.


texts: Libgdx drawing a circle with large radius causes exception

texts:
When drawing a circle using the ShapeRenderer and using a really big radius (in millions, planet/sun size, given in metres) libgdx throws an exception

Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException: 20003
    at com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20.color(ImmediateModeRenderer20.java:116)
    at com.badlogic.gdx.graphics.glutils.ShapeRenderer.circle(ShapeRenderer.java:880)
    at com.badlogic.gdx.graphics.glutils.ShapeRenderer.circle(ShapeRenderer.java:844)
    at com.kacpr.solar.system.Planet.draw(Planet.java:74)
    at com.kacpr.solar.system.SolarSystem.render(SolarSystem.java:66)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:223)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

This didn't happen when I used smaller values.
The question I have is whether I'm doing something wrong using such high numbers for a radius and should scale this down before drawing (I use this radius for some other calculations) or is this a bug?


texts: How to apply code of certain script to another?

texts:
I have a code in my "OnCollider" script to respawn whenever the player dies and has taken an object containing tag 'Respawn'.
1st script: OnCollider ;

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

    public class OnColllider : MonoBehaviour {
        public GameObject Doorfinder;
        public GameObject Door2;
        public Transform Camera;
        public Transform target;
        public GameObject Coin;
        public bool collided;
        public GameObject Playee;
        public GameObject currentRespawn;
        void Start(){
            Door2 = GameObject.Find ("Door0.2");
            Playee = GameObject.Find ("Player");
        }
        public void OnCollisionEnter2D(Collision2D collision){

            if (collision.gameObject.name ==

"scroll") {
            Destroy (collision.gameObject);
            Destroy (Doorfinder);
        }
        if (collision.gameObject.tag == "Fire" ) {
            Playee.SetActive (false);
        }

        if (collision.gameObject.name == "PathFinder") {
            Destroy (collision.gameObject);
            Destroy (Door2);
        }

        if (collision.gameObject.tag == "Coin") {
            Destroy (collision.gameObject);
        }

        if (collision.gameObject.tag == "subVillains") {
            Playee.SetActive (false);
        }
        if (collision.gameObject.tag == "Bramble") {

            Playee.SetActive (false);
        }

        Respawnable (collision);
    }
    public void Respawnable (Collision2D collision){
        if (collision.gameObject.tag == "Respawn") {
            collided = true;
            collision.gameObject.SetActive (false);

        }
        if (collided = true && Playee.activeInHierarchy == false) {
            transform.position = currentRespawn.transform.position;
            Playee.SetActive (true);
            collided = false;
        }
        if (currentRespawn.activeInHierarchy == false && collision.gameObject.tag == "Respawn") {
            currentRespawn = collision.gameObject;

        }

    }

}

2nd Script: Enemy;

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

public class MaxyMory: MonoBehaviour {
    public Vector2 origin;
    public float distance;
    public int layerMask;
    public float sider;
    public Vector2 secondorigin;
    public float bringer;
    public float lesngther;
    public GameObject destroy;
    public Vector2 origination;
    public float middle;
    public float lengther;
    // Use this for initialization
    void Start () {
        origin = new Vector2 (transform.position.x + bringer, transform.position.y + sider);
        origination = new Vector2 (transform.position.x + bringer, transform.position.y + middle);
        secondorigin = new Vector2 (transform.position.x + bringer, transform.position.y + lengther);
    }

    // Update is called once per frame
    public void Update(GameObject Playee){
        Debug.DrawRay (origin, Vector2.right*distance,  Color.red);
        Debug.DrawRay (secondorigin, Vector2.right * distance, Color.cyan);
        Debug.DrawRay (origination, Vector2.right * (distance + 30f), Color.gray);
        RaycastHit2D hit = Physics2D.Raycast (origin, Vector2.right, distance);
        RaycastHit2D anotherhit = Physics2D.Raycast (secondorigin, Vector2.right, distance);
        RaycastHit2D checker = Physics2D.Raycast (origination, Vector2.right, distance + 2f);
        if (hit.collider.tag == "Player" || anotherhit.collider.tag == "Player") {
            Playee.SetActive (false);
        }

    }

}

OnCollider is attached to the player while the enemy script is attached to the enemy itself.


texts: In MySQL, how would I model moves that Pokemon can learn?

texts:
I'm making a Pokemon MMO Game with Unity + SmartFoxServer/MySQL. At the moment I'm creating the base structure for the database.

If you are not familiar with Pokemon Games, every Pokemon can learn only a fixed set of moves. I want to represent this in my database. How should I do it?

Currently I have a pokemon_base table that is storing all the base data of the Pokemon, like name, elemental types, base stats, etc, and a Unique Identifier. I need for every Pokemon inside this table to have a list of learnable moves.

I have these ideas to continue:

Have a field on the Pokemon table containing comma-separated IDs of learnable moves
Have a field on the Moves table containing comma-separated IDs of Pokemon that can learn this move, or
Have another Table with a Field for Pokemon ID and boolean fields for each move

The first one to me seems the better because once I have a Pokemon ID I can get all the moves in a string, which I can split by commas and do my checks. Have I missed something?


texts:
Sorry if this question has been asked in the past, but searching Google and here didn't yield relevant results, so here goes.

I'm working on a fragment shader that implements both conditional/boolean diffuse and bump mapping (that is to say, you don't need a diffuse texture or a normals texture, and if they're not present, they're simply changed to default values).

My current solution is to use a uniform float to say "mix amount". For example, computing the diffuse texel works as:

// Compute diffuse amount scaled by vCol
// If no texture is present (mDif = 0.0), then DiffuseTexel = vCol
// kT[0] is the diffuse texture
// vTex is the texture co-ordinates
// mDif is the uniform float containing the mix amount (either 0.0 or 1.0)
vec4 DiffuseTexel = vCol*mix(vec4(1.0), texture2D(kT[0], vTex), mDif);

While that works great and all, I was wondering if there's a better way of doing this, as I will never have any use for in-between values for funky effects.
I know that perhaps the best solution is to simply write separate shaders for mDif=0.0 and mDif=1.0, but I'd like a more elegant solution than splicing shaders before compiling or writing multiple shader files and keeping each one updated.

Any ideas are greatly appreciated. =)


texts: Path finding in 2D grid for objects that can rotate and bigger than one tile (Tetris)

texts:
I'm trying to check if there is a path between two locations in a Tetris board. On this question it tells how to account for different shapes:
Path finding in grid for objects that occupy more than one tile

But having a shape that can rotate needs a different technique. How should I approach this?


texts: Efficient fog-of-war visibility searching

texts:
Every game I look into that uses fog of war tends to have the AI ignore fog of war completely. I'm starting to see why.

I have a RTS game I'm working on, with lots of units moving around. All units are on a grid, and I use a predefined search pattern to scan the grid points around the unit to find the nearest target. So far so good.

However, I have another unit type who's job it is to run around the map and collect scrap from destroyed units. As with combat units, I want it to look around and select the closest scrap it can find. However, unlike combat units, this search isn't limited to it's own vision radius. It should be able to take advantage of the player's entire fog of war. If another unit or building has revealed some scrap, it should be available for the unit to go pick up.

While scanning the vision radius of a unit is simple, I'm having trouble thinking of an efficient way to determine which grid points to scan in this much larger case. Any grid points within view of a building will be fairly static, but things other units see will change every frame, as they are constantly moving.

The two options I see are to record per-player visibility flags within the grid points themselves, and then (somehow) update those flags each frame, or to just loop through all units and buildings and perform individual searches to build a list of visible scrap. The first would be difficult to keep updated without re-scanning the entire map, and the second would be very redundant if there were many units or buildings in a small area.

Is there another method I could use to build a list of visible scrap within a player's entire fog of war view, given that that view is constantly changing?


texts: How are dynamic blending shadows like this created?

texts: I would like to know, how dynamic shadows, that 'blend' onto other objects, are created.


texts:
Is it possible to change the Field of View vertex shader? I zoom my camera by changing the FoV value. However this will cause the skybox also be zoomed and this is not what I wanted. Is it possible to change the FoV value of the projection matrix in vertex shader?

Specifically, I pass the projection matrix by uniform to a glsl shader. I want to change the FoV value of the projection matrix (to make a new projection matrix) in the vertex shader of the skybox.


texts:
I know that its just the background that scrolls and the player pretty much stays centered.  What I am wondering what technique is more correct when I am implementing a large side scrolling map (I am not using tiles like some other questions I have found).

using a very large map 16000 pixels map, and scrolling that. and create an image list, with maybe 4 4000 pixel maps?

also, lets say I want a box at a certain point in my map. Right now I am just counting the pixels that I am scrolling and once I get to pixel 2000 I insert the box, and scroll it with the background.  Does that seem correct? or is there a better way to do all of this?


texts: How to implment the database for event conditions and item bonuses for a browser based game?

texts:
I am currently creating a browser based game, and was wondering what was the standard approach in making diverse conditions and status bonuses database wise. Currently considering two cases.

Event Conditions

Needs min 1000 gold
Needs min Lv 10
Needs certain item.
Needs fulfillment of another event

Status Bonus

Reduces damage by 20%
+100 attack points
Deflects certain type of attack

I wish to be able to continually change these parameters during the process of production and operation, so having them hard-coded isn't the best way.

All I could come up with are the following two methods:

Create a table that contains each conditions with needed attributes

Have a model named conditions with all the attributes it would need to set them:

conditions
  condition_type (level, money_min, money_max item, event_aquired)
  condition_amount
  prerequisite_condition_id
  prerequisite_item_id

Write it in a DSL form that could be interpreted later in the code

Perhaps something like yaml, have a text area in the setting form and have the code interpret it.

condition_foo:
  condition_type :level
    min_level: 10
  condition_type :item
    item_id: 2

Method 2 looks to be more practical and flexible for future changes, trade off being that all the flex must be done on the code side.

Not to sure how this is supposed to be done, is it supposed to be hard coded? separate config file? Any help would be appreciated.

This will be implemented with Ruby on Rails.


texts: rpg 3d open world map & entity loading-streaming

texts:
Hello I'm a web developer and recently I started reading about game development.
I followed some tutorials regarding c++ and openGL (whatever I could find online because as you know not many up to date openGL tutorials exist.)

I keep wondering in a case of a rpg game with a huge real world(map) and entities(enemies what so ever) how could it be implemented. Meaning you cant load a huge map and the entities all at once obviously... I was thinking of subdividing the map into blocks and each block to even smaller ones so that each block contains (5x5) 25 sub-blocks.

A map could be consisted of many blocks such as the following one which has 25 sub-blocks:

P = Players current sub-block
O = sarounding sub-blocks
X = sub-blocks not yet loaded

Entities will be loaded only for the players current sub-block. Keep in mind that P is not just the player is a mesh a piece of map not very big and not as small as the player is.

X X X X X
X O O O X
X O P O X
X O O O X
X X X X X

And I'm wondering is this a good approach?
I suppose each sub-block has to be a different mesh apparently and then stitch them up together?

CASE 2:

What if I stored the map into 1 big height map or a set of height maps and generate the mesh from that. According to the player's position copy the required image height and width where player is always at the center of it and rearrange the data in the vbo?

I'm sorry if this is a silly question but I simply don't now how to approach this and I can't find any references.Also keep in mind that on such a map animations will also happen.

I would really appreciate it if someone could give some references or explain the architecture for a game such as this.


texts: Best practice for scrollable viewport rendering

texts:
I am working on a tile based game that renders the playing surface in a viewport. I am struggling with getting my head around the mechanics and best practices of rendering a viewport, specifically a scrollable viewport.

Typically the entire playing surface is made up of many adjoining tiles, and will display a portion of the surface to the user. The user will be able to scroll around the viewport by dragging or scrolling (North, east, South, west directions)

What would be considered best practice, for example.

would one render and update every tile in the playing surface whether visible or not (I could see this using potentially a lot of processing time on larger maps with processing and needing to update every tile), or;
should one only render what is visible to the user (and a few additional tiles around the edges to ensure that it looks like everything is rendered and avoid holes in the map)

I am quite new to game programming and would appreciate any thoughts and guidance of best practice in this area


texts: Should I avoid using object inheritance as possible to develop a game?

texts:
I prefer OOP features when developing games with Unity. I usually create a base class (mostly abstracted) and use object inheritance to share the same functionality to the various other objects.

However, I recently heard from someone that using inheritance must be avoided, and we should use interfaces instead. So I asked why, and he said that "Object inheritance is important of course, but if there are lots of extended objects, relationship between classes are deep coupled.

I'm using an abstract base class, something like WeaponBase and creating specific weapon classes like Shotgun, AssaultRifle, Machinegun something like that. There are so many advantages, and one pattern I really enjoy is polymorphism. I can treat the object created by subclasses as though they were the base class, so that the logic can be drastically reduced and made more reusable. If I need to access the fields or methods of the sub-class, I cast back to the sub-class.

I don't want to define same fields, commonly used in different classes, like AudioSource/Rigidbody/Animator and lots of member fields I defined like fireRate, damage, range, spread and so on. Also in some cases, some of methods could be overwritten. So I'm using virtual methods in that case, so that basically I can invoke that method using the method from parent class, but if the logic should be different in child, I have manually overridden them.

So, should all these thing be abandoned as bad practices? Should I use interfaces instead?


texts: How can I programatically generate sprite instances in Unity?

texts:
I want to create a block-based puzzle game that generates blocks as they are required, however I cannot seem to find any good information on how to do something like this using Unity's new sprite system.

Ideally the following would occur:

Generate a random number to determine the type of block
Create a sprite object of correct block type
Display block on screen

I currently have the following:

using UnityEngine;
using System.Collections;

public class Block : MonoBehaviour {

    public SpriteRenderer blockSprite;
    int row;
    int column;

    // Use this for initialization
    void Start ()
    {
        row = 0;
        column = 0;
    }

    // Update is called once per frame
    void Update ()
    {
        // gravity check
    }

    public void GenerateNewBlock()
    {
        int randNumber = Random.Range(0, System.Enum.GetNames(typeof(BlockType)).Length);
        Sprite sprite = new Sprite();

        blockSprite = gameObject.GetComponent<SpriteRenderer>();

        switch (randNumber)
        {
        case 0:
            sprite = Sprite.Create(AssetsLoader.Instance.BlockSprites[BlockType.Water], new Rect (0, 0, 100, 100), new Vector2(0, 0), 100.0f);
            break;
        case 1:
            sprite = Sprite.Create(AssetsLoader.Instance.BlockSprites[BlockType.Fire], new Rect (0, 0, 100, 100), new Vector2(0, 0), 100.0f);
            break;
        }
    }
}

public enum BlockType
{
    Water,
    Fire
}

And an assets loader Singleton class to load in the textures once into memory

using UnityEngine;
using System.Collections.Generic;

public class AssetsLoader : MonoBehaviour
{
    // instance variable to prevent multiple instances of this class
    private static AssetsLoader instance;

    // variables we want to retain state
    public Dictionary<BlockType, Texture2D> BlockSprites;

    // empty private constructor
    private AssetsLoader() {}

    // Property that holds the instance
    public static AssetsLoader Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new AssetsLoader();
            }

            return instance;
        }
    }

    // Use this for initialization
    void Start ()
    {
        BlockSprites = new Dictionary<BlockType, Sprite>();

        Sprite newSprite;

        newSprite = Resources.Load("Sprites/water block") as Texture2D;
        BlockSprites.Add(BlockType.Water, newSprite);

        newSprite = Resources.Load("Sprites/fire block") as Texture2D;
        BlockSprites.Add(BlockType.Fire, newSprite);
    }
}

Can someone please help me understand what needs to be done to create block objects in my scene. Ideally I would only use Sprite objects but I think I might need to load the assets in as Textures in order to get them to display.


texts: Rotating projectile in direction it is moving

texts:
I am using a parabola curve to launch my arrows:

public static Vector3 Parabola(Vector3 start, Vector3 end, float height, float t)
{
    Func<float, float> f = x => -4 * height * x * x + 4 * height * x;

    var mid = Vector3.Lerp(start, end, t);

    return new Vector3(mid.x, f(t) + Mathf.Lerp(start.y, end.y, t), mid.z);
}

I have a projectile that is a simple capsule scaled down to be long and thin like an arrow. I've tried every way to rotate it I could find online, but there is always something off. In order to follow the curve I need the direction between the last position and the new position, so I have been trying things like:

void ParabolaMovement() //Called in Update()
{
    parabolaAnim += Time.deltaTime;

    parabolaAnim = parabolaAnim % 5;

    Vector3 newPos = MathParabola.Parabola(start, target, 5f, parabolaAnim / 5);
    Vector3 dir = newPos - transform.position;
    transform.LookAt(dir);

    transform.position = newPos;
}

As for what is going wrong, it does not point AT the target, which I udnerstand it can't because nowhere do I specify target pos, which I should, but don't know where. I cannot simply tell it to lookat target, since I want it to lookat the direction it is currently going in the curve, but it also needs to face the target.


texts: How to give a ball a following texture trailing effect

texts:
How do I draw copies of the leading texture so that there is a line of the leading ball following behind it? (that don't collide)

So far I have tried to create the effect by placing another graphic 2 pixels off the graphic, but I don't see the second ball being drawn.

spriteBatch.Draw(ballTexture, ballPos, null, Color.White, 0.0f, new Vector2(Ballpos.X +2, ballPos.Y +2), ballSize, SpriteEffects.None, 0);

Thanks.


texts: Difference between "buffer" and "array" in OpenGL?

texts:
When I read doc on webGL or OpenGL there can be seen some patterns in how names of functions and objects are used. But I can't understand the difference between  buffer object and an array.

There are "vertex buffer objects", "vertex array objects" and even some kind of "buffer array" or "arraybuffer".

In OpenGL context, When something is "array" and when it should be called a "buffer" instead?


texts: Minimum number of moves algorithm in Java

texts:
I'm looking to implement the minimum number of moves algorithm for the java game I'm developing but I can't quite figure it out.
Here's an example picture:

There are also some specifications about this:

The solution in the example above is not unique; other solutions would also be valid as long as the "final character layout (or the positioning of the characters in the nodes)" matches a certain condition (I don't think that's very relevant now so won't go into detail). Also, the nodes aren't actually moved, only it's content.
Adjacent elements cannot be swapped (i.e. in the example above, on the starting side's first swap, 'E' couldn't be swapped with neither 'A' or 'B'; B could be swapped with any character but 'E' and so on.)
The same character can be swapped as many times as one wishes. So, for example, 'B', in the starting side of the picture, could be swapped with 'D'
in the first move (B and D trade places) and then 'B' could be swapped with, let's say, 'E' (so B and E trade places).

So how exactly should I approach this, in order to get the minimum moves? I don't need a full solution, but some pseudo-code or a couple of hints would be greatly appreciated!


texts: Path following with turning radius and obstacle avoidance

texts:
I would like to move an object through a path found by A* star but taking into account the object's turn radius and movement speed, while also avoiding possible obstacles during a curve. After some research, I found this article in gamasutra about realistic turns and this question. If I understood correctly, to add smooth turns I just need to create a circle in either the left side of the object or the right (depending on which direction it will rotate) and then move the object along that circle until it reach the point in which it can move straight to the goal. I implemented the code from the article, however I couldn't get it working

The tank is the object I want to move and the boxes are obstacles;
The red Xs are the "waypoints" and the blue line is the line segment
between those points;
The white circle is the tank's turning radius;
The green line is the actual movement the tank would perform taking
its turning radius and movement speed into account;
And the pink
dotted circle represents the "point to leave the circle and start on
the straight line" that I've got with the algorithm;

The first problem is that I'm not sure how to calculate the right place for the pink circle. If I understood correctly, it should be positioned between the end of the green line's curve and the start of the straight one.
The second problem is that, once solved the first, I don't know how to actually move the tank through the "circular" path, while in straight path I could simply take the direction between the current point and the next, and move along that.
Here's my implementation in gdscript
extends Node2D

var speed = 80
var rotation_speed = 1

var goal = null
var velocity = Vector2()

func _ready():
    goal = get_parent().get_node("Goal").global_position

func _physics_process(delta):
    if goal == null:
        return

    var pos = global_position
    var circle_radius = speed / rotation_speed

    var angle_to_circle_center = rotation + PI/2 #rotation - PI/2
    var circle_pos = pos
    circle_pos.x += circle_radius * cos(angle_to_circle_center)
    circle_pos.y += circle_radius * sin(angle_to_circle_center)

    var dx = goal.x - circle_pos.x
    var dy = goal.y - circle_pos.y
    var h = sqrt(dx*dx + dy*dy)
    var r = circle_radius

    if h < r:
        return

    var d = sqrt(h*h - r*r)
    var theta = acos(r / h)

    var phi = atan(dy / dx)
    var Q = Vector2()
    Q.x = circle_pos.x + r * cos(phi + theta)
    Q.y = circle_pos.y + r * sin(phi + theta)

    get_parent().get_node("icon").global_position = Q

Any insight would be appreciated - thanks in advance!


texts: Building multiple android apps via script does not trigger Resolving Android Dependencies

texts:
I have a Unity Project which builds a number of smartphone android apps
Anytime I need to build an app I have a script (SetupApp) that move a bunch of assets in the Resources folder and changes the package name.
As far as I understood changing the package name triggers the tedious process of “Resolving Android Dependencies”, because all the various libraries in Plugins/Android need to be recompiled.
So far so good.
Recently I tried to create a multi-builder, basically it’s a script (MultiBuilder) that takes all the applications that need to be created and, before each, calls SetupApp and then calls  BuildPipeline.BuildPlayer
My issue is that when MultiBuilder calls SetupApp the “Resolving Android Dependencies” is not triggered, creating all the app with the same (wrong) dependencies.
Some thoughts:
Is there a way to force by script the “Resolving Android Dependencies”  process?
Is there a way to wait for the resolving process to be finished and the continue the building process?
Is there a better way to do so?
This goes really beyond my understanding of Unity, any help is very welcome.
Thanks


texts: 2D Infinite scrolling terrain on two axes

texts:
There seems to be a lot of posts about endlessly scrolling backgrounds on one axis, but not much for a 2-axis solution. As Josh Petrie suggested, I'm posting my approach as an answer to see if anyone can improve on it.

Game Requirements:

I'm creating a 2D game for iOS using SpriteKit and Swift, but this paradigm could work for any touch-screen platform. The game involves a player sprite exploring an infinite field of outer space from a top-down 2D perspective. They drag their finger on the screen to move with scrolling behavior similar to panning a map in the Google Maps or Apple Maps apps.

The player should be able to scroll in any direction along the X and Y axes indefinitely. The texture of the 2D space terrain could be generated and drawn programmatically. Or it could take a limited number of textures made by an artist and recycle those images repeatedly to produce the endless terrain.

Planets and other objects will be added to the map, so there will have to be a way to add these into the terrain as well. Initially, these objects can appear at random, but with a frequency that feels natural (i.e. you can't have too many planets or too few). Later, the location of planets will need to be retained so the player can revisit them. So a mapping system will have to be implemented eventually, and that data stored in memory. For now, that is not necessary but a solution that future-proofs against that necessity is preferred.


texts: How can I perform 2D side-scroller collision checks in a tile-based map?

texts:
I am trying to create a game where you have a player that can move horizontally and jump. It's kind of like Mario but it isn't a side scroller. I'm using a 2D array to implement a tile map.

My problem is that I don't understand how to check for collisions using this implementation. After spending about two weeks thinking about it, I've got two possible solutions, but both of them have some problems.

Let's say that my map is defined by the following tiles:

0 = sky
1 = player
2 = ground

The data for the map itself might look like:

00000
10002
22022

For solution 1, I'd move the player (the 1) a complete tile and update the map directly. This make the collision easy because you can check if the player is touching the ground simply by looking at the tile directly below the player:

// x and y are the tile coordinates of the player. The tile origin is the upper-left.
if (grid[x][y+1] == 2){
   // The player is standing on top of a ground tile.
}

The problem with this approach is that the player moves in discrete tile steps, so the animation isn't smooth.

For solution 2, I thought about moving the player via pixel coordinates and not updating the tile map. This will make the animation much smoother because I have a smaller movement unit per frame. However, this means I can't really accurately store the player in the tile map because sometimes he would logically be between two tiles. But the bigger problem here is that I think the only way to check for collision is to use Java's intersection method, which means the player would need to be at least a single pixel "into" the ground to register collision, and that won't look good.

How can I solve this problem?


texts:
I am creating an editor of sorts that allow you to create 3D voxel models. I just got started and have ran into a few errors. Here is what it is producing:

I think the problem has to do with the way I am handling my vertex format (VertexPositionNormalColor) shader or the way either of them are written:

    struct VertexPositionNormalColor {
        Vector3 position;
        Vector3 normal;

        Color color;

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

        public VertexPositionNormalColor(Vector3 position, Vector3 normal, Color color) {
            this.position = position;
            this.normal = normal;
            this.color = color;
        }
    }

Shader code:

struct ColoredVertexToPixel  {
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
};

struct ColoredPixelToFrame  {
    float4 Color        : COLOR0;
};

ColoredVertexToPixel ColoredVertexShader(float4 inPosition : POSITION, float3 inNormal : NORMAL, float4 inColor : COLOR0)  {
    ColoredVertexToPixel Output = (ColoredVertexToPixel)0;

    float4 worldPos = mul(inPosition, World);
    float4 viewPos = mul(worldPos, View);

    Output.Position = mul(viewPos, Projection);
    Output.Color = inColor;

    // TODO: Implement basic lighting

    return Output;
}

ColoredPixelToFrame ColoredPixelShader(ColoredVertexToPixel PSIn)  {
    ColoredPixelToFrame Output = (ColoredPixelToFrame)0;

    Output.Color = PSIn.Color;

    return Output;
}

technique ColoredBlock  {
    pass Pass0  {
        VertexShader = compile vs_2_0 ColoredVertexShader();
        PixelShader = compile ps_2_0 ColoredPixelShader();
    }
}

I also tryed the object creation code in another project with a different effect file and vertex format and it worked fine. This is defiantly a shader/vertex format error as I set each vertex with the exact same color, so maybe the color and position data in the shader is getting with each other?

Any ideas?

Thanks


texts: Rotate an object's scale according camera Y rotation?

texts:
I have a circle-shaped object to which I want to apply a scale of 2, 1, 1.
Then I would like to rotate this scale according to camera's Y axis.
Let me explain with images,
This is the initial state, the blue circle has a scale of 1:

Game started, when camera looks at 90 degrees angles, it works:

But on arbitrary angles like 45 degrees in this case, it doesn't work:

Here is a GIF that shows what is currently happening:

Basically this is what I'd like:
(game paused and rotated the shape to show desired orientation)

To make it clear, object rotation must remain the same, so please don't suggest rotating it.
In other terms, it should always look elongated on the X axis according camera Y angle.
This is the code I have but obviously it is clearly missing something:
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Camera Camera;

    public Transform Target;

    public Vector3 Scale = new Vector3(2, 1, 1);

    private void Update()
    {
        Target.transform.localScale = Camera.transform.TransformVector(Scale);
    }
}


texts:
I am trying to create a generic camera class for a game engine, which works for different types of cameras (Orbital, GDoF, FPS), but I have no idea how to go about it.

I have read about quaternions and matrices, but I do not understand how to implement it. Particularly, it seems you need "Up", "Forward" and "Right" vectors, a Quaternion for rotations, and View and Projection matrices.

For example, an FPS camera only rotates around the World Y and the Right Axis of the camera; the 6DoF rotates always around its own axis, and the orbital is just translating for a set distance and making it look always at a fixed target point.

The concepts are there; implementing this is not trivial for me.

SharpDX seems to have has already Matrices and Quaternions implemented, but I don't know how to use them to create a camera.

Can anyone point me on what am I missing, what I got wrong?

I would really enjoy if you could give a tutorial, some piece of code, or just plain explanation of the concepts.


texts:
I have an image:

I want to detect wheel empty position dynamically, is it possible?

If not possible please let me know, my work involves PHP/XML/Actionscript where actionscript get image url from xml generated by PHP,

User uploads car image through php admin panel, then passes url to actionscript through XML and actionscript should load image and let him choose the wheel and test on the car.

If you have another solution let me know?


texts: Vector2's static methods and the garbage collector

texts:
I discovered that Vector2's static methods return a different Vector2 from the parameters you give them and I'm under the impression that creating new objects and dereferencing old ones on this kind of scale (100's of method calls per update) is bad for the GC.

Is this the case with C# or does XNA pool these Vector2's for use on later method calls?

I ask because I want my entities collision shapes to share the same position Vector2 as the entity itself to eliminate the need to call updateBounds() after practically every position change. However since the methods return a different Vector2 the entities position and its respective bounds' position become differing objects.

Also is it worth making my own Vector2 class and have its methods non static so I can use someVector.add(otherVector) instead of XNA's way?


texts: Applying Y offset to rotation / position script

texts:
I'm using the script stated below to move a spray bottle around a head.

The code works fine: I have assigned the script to the spray bottle, and I have set the head as the target.

However, I was not happy with the center that Unity seems to use for the spray bottle. The spray bottle never perfectly aimed at the center of the head.

To find out what is going on here, I added a long sphere to the spray bottle. Then I moved the sphere until it would perfectly visualize the center that Unity uses. As once can see, Unity uses the bottom of the spray bottle as its center.
I have uploaded a video here to show the effect.

I imagined that I need to tell the script that the center of the spray bottle is different. I would have to include an offset (I guess a Vector3) in order to set the nozzle as the center.

I haven't been able to find out how to plug this "offset" into the script.

Can anybody tell me where / how I could do that?

Thank you very much!

using UnityEngine;
using System.Collections;

[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbitImproved : MonoBehaviour
{

public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;

public float yMinLimit = -20f;
public float yMaxLimit = 80f;

public float distanceMin = .5f;
public float distanceMax = 15f;

private Rigidbody rigidbody;

float x = 0.0f;
float y = 0.0f;

// Use this for initialization
void Start()
{
    Vector3 angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;
}

void LateUpdate()
{
    if (target)
    {
        x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

        Quaternion rotation = Quaternion.Euler(y, x, 0);

        Vector3 nTargetPos = target.position + new Vector3(0, 0.1f, 0);//10 centimetres lower. The original target.position's center would be around the nose. Instead I want the forehead to be the center, that's why I add 10 centimeters to the y position.

        Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * negDistance + nTargetPos;

        transform.rotation = rotation * Quaternion.Euler(0, -90, 0);//compensate for the fact that the spray bottle should face the head (requiring yaw to be yaw-=90)
        transform.position = position;
    }
}


texts: Game Object is Instantiating on same position

texts:
I am working on a small project . But now I have come across a problem . The problem is the prefab is instantiating on the same position .

I want to instantiate a box end to end . The basic set up is as follows : -

Image 3 :- Please see the comment below

Box game object has a parent empty object (Start_point) , and a child empty object (end point) . Those marks the Start and End of that game object .

The game a empty game object (Tile_Gen) which has a C# script as follows :-

using UnityEngine;
using System.Collections;

public class Tile_Gen : MonoBehaviour
{

   public GameObject G_O_01 ;

   public GameObject Current_Tile ;

   public Vector3 Start_Position_Of_Path ;

// Use this for initialization
void Start ()
{
    Start_Position_Of_Path = Current_Tile.transform.GetChild(0).transform.GetChild(0).position;
    Instantiate(Current_Tile , Start_Position_Of_Path , Quaternion.identity);

}

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

public void Path_Generator()
{
    Instantiate(G_O_01 , Start_Position_Of_Path , Quaternion.identity);
// End of tile position = start tile position
    Start_Position_Of_Path = G_O_01.transform.GetChild(0).transform.GetChild(0).position;
    print (Start_Position_Of_Path);
}
}

Here G_O_01 is Start_point prefab , Current_Tile is Start_point .

But this is not instantiating as I wanted . This instantiates all the object at one place .

But I want something like one behind the another , like this :-

Image 4 :- Please see the comments below

So Please help me to figure it out .

Regards NB :)


texts: Torque applies to one wheel, but inconsistently to the other wheel

texts:
I have a GameScript class which is derived by another class WheelScript; it is meant to apply torque to a rigidbody in different directions depending upon the key pressed.

However the result to this is that one of the rigidbodies rotates fine but the other one doesn't (say the right wheel rotates but the left doesn't turn or even if it does, it doesn't move with the same angular velocity as the first one)

Base class:

public class GameScript : MonoBehaviour
{
    public static GameScript instance;
    protected float Force;

    protected virtual void  Print(GameObject gameObject) {
        print(gameObject.name);
    }

    protected virtual void MoveForward(Rigidbody rigidBody, int identifier) {
        if(identifier == 1)
        {
            rigidBody.AddRelativeTorque(-Vector3.forward * Force);
        }
        else
        {
            rigidBody.AddRelativeForce(-Vector3.forward * Force);
        }
    }

    protected virtual void MoveLeft(Rigidbody rigidBody, int identifier) {
        if (identifier == 1)
        {
            rigidBody.AddRelativeTorque(-Vector3.forward * Force);
        }
        else
        {
            rigidBody.AddRelativeForce(-Vector3.forward * Force);
        }
    }

    protected virtual void MoveRight(Rigidbody rigidBody, int identifier) {
        if (identifier == 1)
        {
            rigidBody.AddRelativeTorque(Vector3.forward * Force);
        }
        else
        {
            rigidBody.AddRelativeForce(-Vector3.forward * Force);
        }
    }

    protected virtual void MoveBack(Rigidbody rigidBody, int identifier) {
        if (identifier == 1)
        {
            rigidBody.AddRelativeTorque(-Vector3.forward * Force);
        }
        else
        {
            rigidBody.AddRelativeForce(-Vector3.forward * Force);
        }
    }
}

Child class:

public class WheelScript : GameScript
{
    [SerializeField] private int identifier;
    Rigidbody body;
    [SerializeField] float force;

    private void Start()
    {
         body = GetComponent<Rigidbody>();
         Force = force;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            MoveForward(body, identifier);
        }
        else if (Input.GetKey(KeyCode.A))
        {
            MoveLeft(body, identifier);
        }
        else if (Input.GetKey(KeyCode.D))
        {
            MoveRight(body, identifier);
        }
        else if (Input.GetKey(KeyCode.S))
        {
            MoveBack(body, identifier);
        }
    }
}

and similarly for the other wheel with only difference being that of axis as its axis is (0,0,-1)

Hinge Joint for left wheel is visible in this picture

Hinge Joint for right wheel is visible here in this picture

This is how each wheel is aligned

Hinges are attached to the pivot in the opposite direction as marked in the circle

Also I think I forgot to mention but the WheelScript is attached to both the wheels (it is the script component for both wheels)


texts: box2d's ApplyForce works wrong after cocos2d-x's replaceScene

texts:
i'm practicing making a breakout game, using cocos2d-x 3.x and box2d, referencing here.

i create a ball in the scene's init function and apply force.

when ball hits bottom wall, if i touch screen then the game restart current scene.

after restart the scene, the ball's velocity is not same with the first ball's one. it's slower.

i can't find what's wrong in my code. i need help. here are my code, creating a ball and restart scene.

void GameScene::CreateBall() {

    // create ball texture
    ball = Sprite::create("ball.png");
    ball->setPosition(Point(100,100));
    ball->setTag(1);
    this->addChild(ball);

    // create ball body
    b2BodyDef ballBodyDef;
    ballBodyDef.type = b2_dynamicBody;
    ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
    ballBodyDef.userData = ball;
    b2Body *ballBody = _world->CreateBody(&ballBodyDef);

    // create circle shape
    b2CircleShape circle;
    circle.m_radius = 26.0/PTM_RATIO;

    //create shape definition and add to body
    b2FixtureDef ballShapeDef;
    ballShapeDef.shape = &circle;
    ballShapeDef.density = 1.0f;
    ballShapeDef.friction = 0.0f;
    ballShapeDef.restitution = 1.0f;
    _ballFixture = ballBody->CreateFixture(&ballShapeDef);
    b2Vec2 force = b2Vec2(1500,1500);
    ballBody->ApplyForce(force, ballBodyDef.position); // in here apply force
}

bool GameScene::onTouchBegan(Touch *touch, Event *event) {

    if(gameOver) {
        Director::getInstance()->replaceScene(GameScene::createScene());
        return true;
    }
}


texts: Line Intersection from parametric equation

texts:
I'm sure this question has been asked before. However, I'm trying to connect the dots by translating an equation on paper into an actual function. I thought It would be interesting to ask here instead on the Math sites (since it's going to be used for games anyway ).

Let's say we have our vector equation :

 x = s + Lr;

where x is the resulting vector, s our starting point/vector. L our parameter and r our direction vector.

The ( not sure it's called like this, please correct me ) normal equation is :

x.n = c;

If we substitute our vector equation we get:

(s+Lr).n = c.

We now need to isolate L which results in

L = (c - s.n) / (r.n);

L needs to be 0 < L < 1. Meaning it needs to be between 0 and 1.

My question:
I want to know what L is so if I were to substitute L for both vector equation (or two lines) they should give me the same intersection coordinates. That is if they intersect.

But I can't wrap my head around on how to use this for two lines and find the parameter that fits the intersection point.
Could someone with a simple example show how I could translate this to a function/method?


texts:
I'm working on a small Breakout clone using Cocos2D-JS, without the use of a physics engine.

One of the things that baffles me was how the ball bounces. My friend came up with this:

  inputVector - 2(normalVector * inputVector)

I have no idea how to translate that in code. So I tried with this:

g_Ball.position = this.velocityComputer(cc.p(g_Ball.x, g_Ball.y), cc.p(this.x, this.y));

velocityComputer: function(inVector, thisNVector) {
    var prodVec = cc.pDot(inVector, thisNVector);
    var retVec = inVector - (2 * (prodVec * inVector));
    cc.log(retVec);
    // cc.log(blockNVec);
    return retVec;
},

But g_Ball doesn't change directions, and retVec simply logs NaN.

Any suggestions?

Thanks.