texts: how to do rigidbody movement relative to player rotation in unity c#?

texts:
in my game the player is to walk around a sphere, I'm using rigidbody to apply movement with a joystick like this;
rb.velocity = new Vector3(move.x, move.y)* speed;
The problem is that when a character walks around a sphere, they rotate, so the movement gets messed up, how do I make them move relative to the current rotation and not the world?
I'm new to unity and coding in general so showing example code would help a lot!


texts: How do you render planets without distortion?

texts:
I've recently been working on a little spaceship flying sim in Unity and want to add planets. Up till now, I've been hand modeling them in Blender. But I want to have a way to generate large planets with heightmaps. While researching the topic, I found this video about a voxel planet game and its tech, Here. In the video, they describe a way to render a planet with low distortion. They also relate it to how No Man's Sky does it.

My question is, Are there other methods of rendering planets that have zero distortion?
I would prefer if the answers wouldn't be Unity3D specific since i'm considering switching to Monogame or DirectX.

Thanks in advance!

Edit. I've been asked to describe the distortion.
The distortion is what happens when a cube gets mapped to a sphere. The video suggests a method of using shader warping when on the ground but using the method of squishing a cube to a sphere when in space. This method causes a noticeable warp when going from space to ground because it switches rendering methods. My question is if there is a way to prevent that warp and provide a truly seamless transition from space to ground.

One more edit, I have found another video on a seamless planet engine called Outerra here It seems to have no warping when leaving the atmosphere. It can be seen at 0:50 and at2:22 in this video.


texts: Tangible benefits to speed-coding your personal game projects

texts:
I noticed a few programmers setting time-sensitive challenges for themselves, usually in the area of "write game of type X in Y amount of time" or "write X number of games giving only Y time for each". What are the tangible benefits for setting your workflow in this manner to speed-code for a while? It feels like you have to trade off efficient code to get something done quick. And I suppose adding a final layer of polish isn't a big priority in these challenges, so it's okay to use programmer.

I've made some simple 2D scrolling shooters and puzzle games a few years ago and out of stupidity I deleted most of my code. So now I'm curious about using the speed-coding approach to get a couple simple things done again, and get myself more into game logic.


texts: Unity tilemap spacing between imported sprites

texts:
What am I missing here? Is Unity's tilemap limited to size 32x32?

I am trying to understand why my sprites in my Unity tilemap are spaced apart from one another such that if I paint them into the scene the tiles are centered in the grid's cells in an undesirable way.

I want my grid to be size 8x8 pixels and I want my sprite sheet to be imported in with pixels per unit set to 32 so that it matches the pixel size of my character and the rest of my art.

I've tried adjusting the import size setting and that did nothing.
I've tried changing the scaling of the grid, but that results in a smaller grid with smaller sprites still centered in the cells.

The only thing I've found that "fixes" this is to re-slice my sprite sheet at 32x32, but that results in tiles that are larger than what I am aiming for.


texts:
I am busy with a pet project where I am trying to create a Collectible Card Game in 3D.

These cards have Hp and Damage etc. but I cannot find a way to neatly display these values.
I tried to use a TextMesh, but all the text just blends into each other if the cards happen to overlap (eg. when the cards are in the hand).

Currently, I am using a plane for each value, and then changing the Material used on that plane, to match the value (eg. a '3' Material if the Damage is 3). It works, but I can't help to think that there has to be a better way.

Is there a way to dynamically display values on a plane so that it looks like the value is a part of the card itself, without changing the materials every time a change occurs? Or suggest anything else that would suit my needs?

If I am taking a horrible approach, you're welcome to nudge me in a better direction.

Thanks in advance


texts: How to "place" object in a 3d world without overlapping them ?

texts:
I would like to place object  in a 3d world "like minecraft player can do".

What I'm trying to do is to allow the user to place objects, without overlapping them (like in minecraft you can do).

So if the player try to place an object partially over another, my  game automatically "move and place" the object in the allowed position.

What can be the right approach ?


texts:
I'm new to UDK, and am using it to develop a survival-horror game based heavily on shadows.

My question is short:  is there a way to create an actor that, when rendered, ONLY renders its shadow (not itself)?

If UDK can't do this, is there any other engine (Unity, CryEngine, Source) that can?


texts: How is structural analysis done in games (e.g.: bridge building, Dig or Die, and 3D)?

texts:
From what I understand a typical interactive truss system would need substantial calculations since every component affects the entire system. I think you could arbitrarily stop at a given number of iterations at cost of accuracy in the simulation, but I don't know if that's the approach these games use (bridge building games are an example of truss systems). On the other hand, games like Dig or Die have a quite complex structural system that also takes torque into account (I believe) and compression and is very fast and works on very extensive systems. I guess the basic calculations could be similar, but if not I'm interested in both approaches.

Do you guys know how these are made? Do they have an arbitrary limitation or do they use a different algorithm altogether? Also, I guess whatever you guys come up with can be applied to 3D systems but if not or if it's not obvious please at least give a clue on how you could use it for 3D since I'm interested in this for both 2D and 3D games.

I know I'm not supposed to thanks here but I find unfair not to at least thank you for your time in advance, I hope this paragraph don't get removed.

EDIT: If I were to make a guess I'd say Dig or Die stores vectors for each block and then run an iterative algorithm up to a point that the extra accuracy in the simulation is meaningless for the limits of the system (for example, the system would be too large to not collapse anyway), so it's limited by a semi-arbitrary (because it's based on application) number of iterations. But I could be wrong.


texts:
I am trying map polar coordinates to points on a cube. I was able to map the front, back, left and right faces of the cube, but I am struggling with the top and bottom. Here is what I have:

/// <summary>
/// Converts polar coordinates to uv coordinates on a cube.
/// </summary>
/// <param name="p">The polar coordinate; p.x = longitude, p.y = latitude.</param>
/// <param name="face">The face of the cube that p maps to.</param>
/// <returns>The xy coordinate on the cube face.</returns>
private Vector2 PolarToCubeFace(Vector2 p, out CubemapFace face)
{
    face = CubemapFace.Unknown;
    Vector2 result = Vector2.zero;

    float lng = p.x; // East-to-West.
    float lat = p.y; // North-to-South.

    if (lat >= 45 && lat <= 135){ // Front, back, left, or right face.
        face = (lng > 0 && lng <= 90) ? CubemapFace.PositiveZ :
            (lng > 90 && lng <= 180) ? CubemapFace.PositiveX :
            (lng <= -90 && lng > -180) ? CubemapFace.NegativeZ :
            CubemapFace.NegativeX;

        result.y = (lat - 45) / 90f;
        result.x = mod(lng, 90) / 90f;
    }
    else{ // Top or bottom face.
        // Need help here.
    }
    return result;
}


texts: FPS drops when I maximize the game tab in Unity Editor

texts:
I have a simple unity scene with some primitive objects like cubes and spheres. Most of the objects are static and I made backed GI for lighting, The light is a point light. I also used unity post-processing asset for the depth of field.
 FPS in normal game window size is about 500 but when I maximize the Game tab, FPS goes around 30. Why does this happen?
FPS 500

FPS 30


texts: Making an indie with friends: Legal considerations

texts:
I am close to finishing a game I am making with 3 friends. 1 other coder, and 2 graphic designers. We agreed from the start to split revenue (40/40/10/10).

However we have no contract, and I know that I don't own the graphics/sounds in my game just because "my friend made it". What steps should we take to make sure that all graphics/sounds that were provided by my friends, are actually owned by me (the company).

We have a budget of $0 so hiring a lawyer is not an option, should we draft our own contract regarding the revenue share?


texts: Best Practices for combining animation and logic

texts:
In Games I often run into this kind of scenario:

The Game Logic decides something happens, and of course the logic does so instantly. But the Game also has animations depending on the logic. Like player died -> play death animation -> respawn.
But the logic can't wait for the animation so we have to work around that.

Or take for example Starcraft 2 siege tanks as morphing units on click and they start the siege animation, but in what state is the logic. Is there a state for each animation too? Is it just a Flag ignoring everything as long as it is animating?

It tends to become really messy as i am including more and more animations.

Hope someone can give me a hint.


texts: How can I make a solitaire game that can be solved?

texts:
It was not difficult to mix the cards and make them in solitaire format.

But sometimes there are games that can't be solved. (For example in 3 turn mode)

How can I make sure that the game can be solved?


texts:
I have been wondering now for quite some time, how certain animated texture effects are done, specifically involving light effects.

Some good examples of what I mean are the green bridges in Darkspore, who have a pulsating light effect (pic), the light bridges in Portal or some spell effects from Oblivion (pic).

Are those effects purely done with shaders? And if so, how would you go about doing them? If I for example wished to create an effect, which would send little lightning bolts from a character models feet to the top as illustration that he got electrocuted, how would that work?

To my person:
Although I am proficient in programming, I am mostly a beginner, when it comes to shaders. I understand most of the math behind it, but have almost no practical experience with them.

I hope you can clear things up for me a bit!

Thanks you for reading and in advance for any help!
Christoph


texts: Unity 5.5.1f1 new UI system: Button in scrollview is not working on Android. Is this known issue? Is there a workaround?

texts:
It works perfectly in the editor, but on Android it only sometimes registers an OnClick when I press it with my finger.

I'm on Unity 5.5.1f1

Is this a known issue? I'll post some videos of it if no-one has seen this before.

The scrollview is based on the default one from the Create\UI\scrollview menu
Ive added a vertical layout group to it, to which I add prefabs that contain buttons. These are the buttons that are not working.
The canvas is in front of the camera in worldspace and is scaled down to 0.02 in X and Y

VVVVVVVVVVV  UPDATE VVVVVVVVVVVVV

I wrote my own workaround using 2D colliders instead of buttons
The colliders are registering hits just fine.
But when I wrote a class to not register hits if the scrollview moves, I get similar behaviour!
Heres the crude little workaround class I wrote..

public class ScrollButton : MonoBehaviour
{
    public StoreItem Item;

    bool FingerDownOnMe;

    public void BeOnClicked()
    {
        VisualDebuggerRef.SetTxt("a store button" + " " + Random.Range(0, 10000));
        FingerDownOnMe = true;
    }

    // This is called on all these objects whenever the scrollview moves
    public void ScrollviewMoved()
    {
        FingerDownOnMe = false;
    }

    void Update()
    {
        // 'UppedthisFrame' will be true whenever any touchs phase == TouchPhase.Ended
        if (Refs.man.Clickdetect.UppedthisFrame && FingerDownOnMe)
        {
            FingerDownOnMe = false;
            Item.ButtonHit();
        }
    }
}

I'm guessing Unities UI classes work in a somewhat similar way to my workaround one. The problem is that the scrollview is registering as being moved when it should not be. This may be because of my test device which is an S7. Maybe the touch resolution is so high it is registering movement that is smaller than one pixel??

Also maybe the fact the the entire canvas has been scaled down could be affecting this? Say Unities classes have a distance threshold, if they are not taking into account scale then working on a scaled down canvas might make the distances they are using too big, so the threshold is reached too easily

Im going to add a distance limit to my workaround...

VVVVVVVVVVVVV UPDATE2 VVVVVVVVVVVVVVVV

This workaround code using colliders works perfectly..

public class ScrollButton : MonoBehaviour
{
    const float scrollThreshold = 0.25f;

    public StoreItem Item;

    bool FingerDownOnMe;
    Vector3 HitPos;

    public void BeOnClicked()
    {
        //VisualDebuggerRef.SetTxt("a store button" + " " + Random.Range(0, 10000));
        FingerDownOnMe = true;
        HitPos = transform.position;
    }

    void Update()
    {
        // 'UppedthisFrame' will be true whenever any touchs phase == TouchPhase.Ended
        if (Refs.man.Clickdetect.UppedthisFrame)
        {
            if (FingerDownOnMe && Mathf.Abs((transform.position - HitPos).y) < scrollThreshold) Item.ButtonHit();

            FingerDownOnMe = false;
        }
    }
}

I'm going to report this issue as a bug to Unity


texts: Accessing Canvas and Button components in a scene

texts:
I have a scene with the following hierarchy:

This is game scene and the game manager is a singleton with the following variable fields:

// canvas
public Canvas PauseCanvas;
public Canvas MainMenuCanvas;

Before implementing singleton, I assigned them from the inspector. Now that the game manager is singleton, I need to assign them through script on level load. I can see one solution to this situation:

Getting all canvas components through GetComponents<Canvas>() and then iterating and checking their name fields to assign them accordingly or maybe using LINQ.

What I want to ask is: Is there a name-based search method just like finding game objects with name GameObject.Find("Name") that is applicable for Components?


texts:
I have a ball in a game that rolls around just fine with Rigidbody.AddForce().  I have other non-physics balls, however, that I control directly with Rigidbody.MovePosition().

It seems that no matter what I do, no matter how interpolation and collision detection are set, the ball does not "roll" when moved with Rigidbody.MovePosition(). It teleports, but IsKinematic is not set , as instructed by the documentation.

How do I get the ball to roll properly with Rigidbody.MovePosition()? Alternatively, if that's not possible, how do I calculate the rotations manually?


texts: Garry's Mod gamemode scripting (lua) - How do I tell if an object is inside a hollow cylinder?

texts:
I'm fiddling about with gMod trying to make a gamemode where you have to throw a piece of cake into a cylinder that spawns on the map.

This is the code I'm using to spawn the cylinder:

local ent = ents.Create( "prop_physics" )
ent:SetModel("models/props_phx/construct/windows/window_curve360x1.mdl")
ent:SetPos( Vector(math.random(100,2500), math.random(1500,-1000), 150) )
--ent:SetPos( math.random(-1500,-2500), math.random(-1500,-2500), 100 )
ent:Spawn()

cleanup.Add( self.Owner, "props", ent )

undo.Create( "Spawned_Cylinder" )
undo.AddEntity( ent )
undo.SetPlayer ( self.Owner )
undo.Finish()

The cake throwing part is basically just a SWEP that shoots the 'cakehat' prop. How would I test whether there is a piece of a cake inside the cylinder?


texts: (XNA) Stretching Images (Sprites) without Blur (Rasterizing?)

texts:
thanks for clicking on this question although it has likely one of the most un-specific and confusing titles on this site. I am somewhat new to XNA and I have only posted 1 question on this site before which I didn't understand the answer to fully, but I'll give it another go.

I am looking to create a game which allows the user to either go full-screen or re-size the window to a few preset values, like many mainstream games nowadays allow you to do.
I believe I know how to do this in XNA, the problem is, when I toggle full-screen, and it stretches the sprites, they appear blurry.

I know this is a very obvious problem, as stretching = blur (logically). The thing is, I was wondering if there was a way to make it so regardless of the zoom, your sprites look crisp and not blurry? I asked a friend of mine in real life and he said something about rasterizing (which i don't know anything about). The only other thing I can think of

I've seen this done a few times in Flash. For examples of what I mean the only game I can think of is Super Smash Flash 2. It seems regardless of the screen size, most of the sprites and images appear crisp, even on the largest of screens.

If anybody knows anything about this, please share!
-Thanks.


texts: Keeping Android Screen bright during Game

texts: I have a game that uses the accelerometer to move a guy back and forth on the screen.  After a few seconds the screen goes dim.  Is there any way to keep it alive and bright during the game activity?


texts:
I don't really understand how to use the in / out keywords in GLSL, and google is being uncharacteristically unhelpful.

What exactly do they do? How would I use them if, for example, I want to pass a varying variable set per vertex to the fragment shader?

Literally every tutorial I find uses the varying / attribute keywords and that's not helpful.


texts: Shouldn't fragment lighting have the same effect as vertex lighting with only ambient and diffuse lights?

texts:
With infinite light source and only ambient and diffuse lights — no specular light, it seems the rendering results of vertex lighting and fragment lighting should be the same, because all the lighting calculations are linear and it means calculation-then-interpolation and interpolation-then-calculation should be the same. However, the actual results are still not exactly the same, with fragment lighting still smoother. What did I misunderstand? Or is it just because of loss of arithmetic precision during calculation-then-interpolation?

Code of fragment lighting:

// Vertex shader

attribute vec4 Position;
attribute vec3 Normal;

uniform mat4 Projection;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;

varying vec3 EyespaceNormal;

void main(void)
{
    EyespaceNormal = NormalMatrix * Normal;
    gl_Position = Projection * Modelview * Position;
}

// Fragment shader

varying mediump vec3 EyespaceNormal;

uniform highp vec3 LightPosition;
uniform highp vec3 DiffuseMaterial;
uniform highp vec3 AmbientMaterial;

void main(void)
{
    highp vec3 N = normalize(EyespaceNormal);
    highp vec3 L = normalize(LightPosition);
    highp float df = max(0.0, dot(N, L));

    lowp vec3 color = AmbientMaterial + df * DiffuseMaterial;

    gl_FragColor = vec4(color, 1);
}

Code of vertex lighting:

// Vertex shader

attribute vec4 Position;
attribute vec3 Normal;

uniform mat4 Projection;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;

uniform highp vec3 LightPosition;
uniform highp vec3 DiffuseMaterial;
uniform highp vec3 AmbientMaterial;

varying lowp vec3 Color;

void main(void)
{
    highp vec3 EyespaceNormal = NormalMatrix * Normal;

    highp vec3 N = normalize(EyespaceNormal);
    highp vec3 L = normalize(LightPosition);
    highp float df = max(0.0, dot(N, L));

    Color = AmbientMaterial + df * DiffuseMaterial;

    gl_Position = Projection * Modelview * Position;
}

// Fragment shader

varying lowp vec3 Color;

void main(void)
{
    gl_FragColor = vec4(Color, 1);
}


texts: Does the feature level affect multisampling?

texts:
I'm using DirectX 11 with the feature level 9_3 even though my computer could run 11_0, but I want to support older hardware as well.

I'm using CheckMultisampleQualityLevels to check whether multi sampling with the given samplecount is supported or not. However it returns 1 for quality with 4samples. And with 8samples it returns 0 (so its not supported). With feature level 11_0 CheckMultisampleQualityLevels returns 1 for 8samples. I'm using a AMD/ATI Radeon HD5830. In the most DirectX9 games I can still use 8x antialiasing. So why is it not supported in DX11 with a lower feature level.

Another point is it seems like 4samples doesnt really affect the output:

With mutlisampling disabled the result is the same. I'm sure that I configurated ms correctly.. even in the Depthbuffer.

Whether I enable AntialiasedLineEnable in the RasterizerDesc or not the output is still the same.

I searched in MSDN but I couldn't find any more information about multisampling.

EDIT: The blacklines in the picture are outlines made in the pixelshader


texts: How can I produce 3D environments for VR from HDRI images?

texts:
I have a question regarding to the HDRI maps as many some of you have a bit of experience in this field especially for Oculus Rift platform!

I've been trying to achieve a 3D landscape from this HDRI map. (Also I highly recommend this website for others :)!)

I even decided to render in Maya few images from the orthographic perspective but unfortunately still no luck.

See the results here on YouTube.

Is there any other method to reconstruct 3D models just from images and use them to create environment?


texts: How can I add these bones to my meta human? Or is there a way I can make virtual bones count when retargetting?

texts:
Paid for animations thinking they would be fine and they mostly are but... the hands are using these IK bones that I do not have. Is there a way I can add the bones to my meta skeleton within unreal? I tried creating virtual bones but they dont seem to come up in the retarget manager :( Also, I can only seem to add one virtual bone to the root whereas both the foot and hand IK root bones are parented to the root bone here.

Any help would be massively appreciated!


texts: Reading from depth textures always returns 1

texts:
I create a packed depth/stencil texture and attach it to a framebuffer like this:

glGenTextures(1,&_depthStencilTexture);
glBindTexture(GL_TEXTURE_2D,_depthStencilTexture);
//set filtering to gl_nearest, not shown cause not important
glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH24_STENCIL8,width,height,0,GL_DEPTH_STENCIL,GL_UNSIGNED_INT_24_8,nullptr);

//... create framebuffer and attach some color attachments
glFramebufferTexture(GL_FRAMEBUFFER,GL_DEPTH_STENCIL_ATTACHMENT,_depthStencilTexture,0);

The creation of the framebuffer causes no OpenGL status errors.

In terms of usage for depth and stencil testing, the texture/attachment seems to work correctly. If I disable depth testing, I get the usual artifacts of objects in the back being drawn over objects in the front if they are drawn in the wrong order. If I disable stencil testing, the effects I'm using related to that don't work anymore (I'm masking out areas that shouldn't be lit by the lighting pass). Also, if I simply don't attach the depth/stencil buffer to the framebuffer, the related tests stop working (as expected).

However, reading from that texture in a shader always returns 1 if I read the depth part, and 0 if I read from the stencil part.

I confirmed this via glReadBuffer(GL_DEPTH_STENCIL_ATTACHMENT) and glReadPixels. All integers read show up as 0xffffff00, directly after clearing them via glClear and a black clearcolor and also after the screen is drawn full of stuff.

Drawing to and reading from the rest of the attached textures (four color buffers for now) works fine.

I have to note that I'm not actually manually drawing anything to the depth-stencil attachment in the fragment shader when rendering - I'm assuming OpenGL automatically draws depth and stencil values to the correct buffer.

What could be the cause of these incorrect values showing up when reading from the texture?


texts: How to access bottom canvas layer in HTML?

texts:
I have such html:

<div id="main_window">
 <canvas id="canvas_hex_logic" width="200" height="100"></canvas>
 <canvas id="canvas_ground" width="200" height="100"></canvas>
</div>

and css:

#canvas_hex_logic{
 position: absolute;
 top:31px;
 left:201px;
 z-index: 0;
}
 #canvas_ground{
 position: absolute;
 top:31px;
 left:201px;
 z-index: 1;
}

in #canvas_hex_logic I'm rendering mask for my hexagons:

over it I'm placing ground layer:

part of JS code, for picking color under mouse:

  ..... mouse event handler above .....
  var c_hex = document.getElementById("canvas_hex_logic");
  var ctx_hex = c_hex.getContext("2d");
  ..... ..... ..... ..... ..... .....
  var color = ctx_hex.getImageData(mouseX, mouseY, 1, 1).data;

This code working, if #canvas_hex_logic is on tom of other layers.

So, question is - how to pick color under mouse from #canvas_hex_logic layer when it is overlayed with another layer?

Thanks!


texts: Can copying assets be legal if I'm not intending to make money?

texts:
I very recently started going through game development tutorials and I was thinking of trying to mimic a game I know as closely as possibly just to see if I can do it as a first project.

I wouldn't at all be wanting to sell this game but would I be able to show this in some kind of online portfolio so long as I mention that none of the assets are mine and give credits to the relevant companies/people?


texts:
I tried to implement a simple movement to my object. My object moves perfectly fine but I'm having issues with its collision. When I keep on moving object towards the obstacle/ground, collision are jittery.
Here the code for what I've written.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TempScript : MonoBehaviour
{
    [SerializeField] float walk_speed = 5f;
    [SerializeField] float jump_speed = 10f;
    [SerializeField] float max_up = 7f;
    [SerializeField] float max_low = -1.5f;

    void Update()
    {

        PlayerMovement();

    }
    void PlayerMovement()
    {

        if (Input.GetKey(KeyCode.W) && transform.position.y <= max_up)
            transform.position = transform.position + Vector3.up * jump_speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.S) && transform.position.y >= max_low)
            transform.position = transform.position + Vector3.down * jump_speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.D))
            transform.position = transform.position + Vector3.right * walk_speed * Time.deltaTime;

        if (Input.GetKey(KeyCode.A))
            transform.position = transform.position + Vector3.left * walk_speed * Time.deltaTime;
    }

}

The cube goes below the ground and bounces right back up. making it look like its jittering.
what i want is movement should stop when its colliding with object. just like it happens with addForce method.
for now you can ignore max_up and max_down variable, it was just to make sure its in the camera.


texts: Component based game engine and dependencies - singletons

texts:
I am thinking about how to create component based game engine.
I understand that all things should be very similar as in Data Oriented Design (each object is a collection of various structures as Position, 3D Model, Health, Damage etc.), but I don't understand how should I handle the very big project.

I made one game in XNA a while ago and when I tried to create such component based game engine - I ended up having many singletons. Many systems depend on each other and I had to use for example Terrain subsystem to handle AI - so I had to make singletons.

How should I organise the game engine so that I wouldn't have singletons? Is it even possible when I have many dependencies?

Also when I created many Entities I found the problem or repetition of code. If I want to for example make AI for few kinds of enemies - some code can be the same for various enemies (Initializing AI, beginning of AIUpdate function) - it appears that inheritance would be best for such case, but then it isn't component based architecture (or Data Oriented Design) anymore...


texts: Abstract games that are hard to play for AI/computer?

texts:
Do you know any abstract multi- or single-player game that is hard to play for AI/computer but not so hard for humans?

Being simple and popular is better.


texts: Is there a specific library to handle the collision system of a big game world like WoW, or any physics library will work?

texts: Nothing else to add. Is there a specific library to handle the collision system of a big game world like WoW, or any physics library like ODE will work?


texts: Need help with using Player Prefs to save number of coins collected

texts:
I'm using unity 3D to make a game where the character collides with coins in order to collect them. When playing the game, the player should start out with zero coins and each time he collides with a coin, the amount should increase by one. On a main menu scene, the total number of coins (that have been collected across multiple games) should be displayed. The total number of coins is being displayed on the main menu but once in the gameplay scene, the total number of coins is being displayed there too (where it's supposed to start at 0 and then increase by 1 each time a coin is collected). Here is the script I use for when the player collides with a coin:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CoinScript : MonoBehaviour
{
    void OnTriggerEnter(Collider target)
    {
        CoinScoreManager.coinAmount += 1;
        Destroy(gameObject);
    }
}

Here is the script I use to manage the UI and coin number in the game play scene:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CoinScoreManager : MonoBehaviour
{
    public static int coinAmount;
    public Text coinText;

    void Start()
    {

        coinAmount = PlayerPrefs.GetInt("CoinAmount");
    }

    void Update()
    {
        coinText.text = coinAmount.ToString();
        PlayerPrefs.SetInt("CoinAmount", coinAmount);
    }
}

Here is the script I use to manage the UI and total coin number in the scene with the main menu:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MainMenuController : MonoBehaviour
{
    int coinAmount;
    public Text coinAmountText;

    void Start()
    {
        coinAmount = PlayerPrefs.GetInt("CoinAmount");
    }

    void Update()
    {
        coinAmountText.text = coinAmount.ToString();
    }

}

I think the problem is in the second script shown above. In the Start function I'm calling the coinAmount which is the same variable used to show the total coin number. I think that's the problem but I'm not really sure how to fix the problem as I'm still kinda of new to Unity and programming. Please let me know if there's anything else you need to know about the game in order to figure out how to fix this. Thanks for your help!


texts: In PHP, how do I implement multiplayer "rooms" for a turn-based game?

texts:
I'm working on a multiplayer checkers game. I want to let players choose another connected player and invite him to play. I have a working game engine and rendering, but I'm stuck on the multiplayer part.

This is specifically a web-based game.

How can I know whether a player is connected?
How can I detect when a player closes the browser, and set them to disconnected?
When a player sends an invitation to another, how do I let the first player know whether the other accepted?
How do I connect 2 players on a same game and send their moves to each other?


texts: How can I make Maya or Blender model work with mecanim?

texts:
I'm working on a simple game project, where I need a stick figure. Due to being stubborn and the desire to learn a new skill, I want to make the stick figure myself! I have followed several tutorials in both Maya and blender. For Maya, I'm using the student version. I have my stick figure rigged within Maya and blender, both utilizing their respective bone tools. I can manipulate their limbs well, enough. However, I can't seem to get the models to work with Mecanim.

I have the Kinect adapter for the PC and would like to be able to use it to create the animations utilizing a tool such as the Kinect v2 mocap animator.

How I can get my model to work with Kinect based mocap?


texts: How can I determine trajectory from distance and time, without initial velocity?

texts:
I'm attempting to develop a Mortar that needs to lead it's shot to the target enemy. The shot will have a pre-determined constant flight time of (2.5 seconds) and it will have where the enemy should be after that time (if the enemies motion is constant).

I'm struggling to figure out the proper equation to get initial velocity (and fire angle required) from just the distance from the predicted location, and the amount of time taken (2.5 seconds).


texts: Shadow map: depth texture always returns 0

texts:
I'm implementing a shadow map for the sun light in my voxel engine using a depth texture attached to a framebuffer. But when I sample the depth texture during the normal pass, the value returned is always 0.

Here is the shadow map initialization :

    // Create and configure the depth texture
    shadowMapTextureId = GL11.glGenTextures();
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, shadowMapTextureId);
    GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_DEPTH_COMPONENT, shadowMapWidth, shadowMapHeight, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (FloatBuffer) null);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL13.GL_CLAMP_TO_BORDER);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL13.GL_CLAMP_TO_BORDER);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL30.GL_COMPARE_REF_TO_TEXTURE);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_FUNC, GL11.GL_LEQUAL);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);

    // Create the framebuffer and attach the depth texture
    shadowMapFramebufferId = GL30.glGenFramebuffers();
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, shadowMapFramebufferId);
    GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, shadowMapTextureId, 0);
    GL11.glDrawBuffer(GL11.GL_NONE);
    GL11.glReadBuffer(GL11.GL_NONE);

    if (GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) != GL30.GL_FRAMEBUFFER_COMPLETE)
        Voxer.error("Shadow map framebuffer creation");
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);

And the fragment shader sampling the depth texture :

    #version 330 core

    uniform sampler2DArray diffuseTextures;
    uniform sampler2D shadowMap;

    in vec3 pass_TextureCoord;
    in vec4 pass_ShadowCoord;
    in float pass_Lighting;

    out vec4 out_Color;

    void main(void)
    {
        out_Color = texture(diffuseTextures, pass_TextureCoord);

        float shadowFactor = 1.0;
        vec4 shadowCoordPostW = pass_ShadowCoord / pass_ShadowCoord.w;

        if (pass_ShadowCoord.w > 0.0f && shadowCoordPostW.x > 0 && shadowCoordPostW.y > 0 && shadowCoordPostW.x < 1 && shadowCoordPostW.y < 1)
        {
            float shadow = texture2D(shadowMap, shadowCoordPostW.xy).x;
            float epsilon = 0.00001;
            if (shadow + epsilon < shadowCoordPostW.z)
                shadowFactor = 0.5;
            // I can replace with this to show that the value is always 0
            // if(shadow == 0)
            //  shadowFactor = 0.5;
        }

        out_Color.rgb *= shadowFactor * pass_Lighting;
    }

I use the same projection matrix for the main camera and the sun camera (it's a perspective matrix), so I know the terrain is in the view frustum.

I used this example : https://github.com/cforfang/opengl-shadowmapping


texts: I have some experience in creating, however I like to have some well written reference material to help me produce better products.  Are there any game design books that are not aimed at a particular programming language?


texts:
I am trying to implement moving random hills in SDL. I am using midpoint displacement algorithm to create some random terrain and I have also accomplished to move the terrain too. But the problem is that the terrain repeats itself after certain period of time. Why is that exactly happening and how to rectify it. Here is my source code.

#include <SDL2/SDL.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
SDL_Window* gWindow = NULL;
SDL_Renderer* gRenderer = NULL;
int arr_size = pow(2.0,11.0) + 1;
int terrain_array[10000];
float roughness = 0.5;
int intial_displacement = 150;
int count = 0;
bool init()
{
    bool success = true;
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        cout << "SDL could not initialize. SDL_Error: " << SDL_GetError() << endl;
        success = false;
    }
    else
    {
        if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
        {
            cout << "Linear texture filtering not enabled.\n";
        }
        gWindow = SDL_CreateWindow( "Midpoint_Displacement_Algortihm", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        if( gWindow == NULL )
        {
            cout << "Window could not be created. SDL_Error: " << SDL_GetError() << endl;
            success = false;
        }
        else
        {
            gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
            if( gRenderer == NULL )
            {
                cout << "Renderer could not be created. SDL_Error: " << SDL_GetError() << endl;
                success = false;
            }
            else
            {
                SDL_SetRenderDrawColor( gRenderer, 96, 96, 96, 96 );
            }
        }
    }
    return success;
}
void close()
{
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;
    gRenderer = NULL;
    SDL_Quit();
}
void initializeArray()
{
    for(int i = 0; i < arr_size; i++)
    {
        terrain_array[i] = 0;
    }
}
void generateTerrain(int leftindex, int rightindex, int displacement)
{
    if((leftindex + 1) == rightindex)
        return;
    int midindex = floor((leftindex + rightindex) / 2);
    int change = ((rand()%1) * 5 - 1) * displacement;
    terrain_array[midindex] = (terrain_array[leftindex] + terrain_array[rightindex]) / 2 + change;
    displacement = displacement * roughness;
    generateTerrain(leftindex, midindex, displacement);
    generateTerrain(midindex, rightindex, displacement);
}
void drawTerrain()
{
    int start_point = 1;
    int i;
    SDL_SetRenderDrawColor( gRenderer, 96, 96, 255, 255 );
    for(i = 1; i < arr_size; i++)
    {
        SDL_RenderDrawLine( gRenderer, start_point, SCREEN_HEIGHT, i, (terrain_array[(count + i)%arr_size] + 3 * intial_displacement));
        start_point = i;
    }
    count++;
}
int main()
{
    initializeArray();
    if( !init() )
    {
        cout << "Failed to initialize\n";
    }
    else
    {
        bool quit = false;
        SDL_Event event;
        while( !quit )
        {
            while( SDL_PollEvent( &event ) != 0)
            {
                if( event.type == SDL_QUIT )
                {
                    quit = true;
                }
            }
            generateTerrain(0, arr_size - 1, intial_displacement);
            SDL_SetRenderDrawColor( gRenderer, 96, 96, 96, 96 );
            SDL_RenderClear( gRenderer );
            drawTerrain();
            SDL_RenderPresent( gRenderer );
        }
    }
    close();
    return 0;
}

I am new to this stuff and trying to learn.
This is what it looks like.


texts: How can I implement an aiming system like the Tank Stars mobile game?

texts:
I have been trying to implement the same aiming system as in Tank Stars, but I got a little stuck. I implemented simple stick aiming, which basically aims towards the stick movement.

In Tank Stars, it is much different compared to the simple aim stick. It remembers the last position and uses it as something like a pivot point.

I tried to implement a virtual pivot point as in the image given. The red circle is a virtual pivot. The green circle is the stick center point, and the green arrow is the supposed stick movement. This implementation kind of works, but I don't understand how I should update that pivot point.
Is my approach correct? What is the name of this aiming system? I need a bit of help with the math behind it.


texts: Why does this Unity code work as expected only with the while loop?

texts:
In unity, in C#, I have the following code in Awake():

Awake()
{
    Transform obj = InstantiateTarget();
    //the bizarrely required and "working" loop
    while (transform.childCount > 0)
    {
        //assign all current children to the replacement object
        foreach (Transform t in transform)
        {
            t.parent = obj;
        }
    }

    Destroy(gameObject);
}

Without the while loop, some random set of the transforms children are destroyed by that end Destroy. With the while, it works exactly as expected (all transform's children become obj's children).

Also, surely with it, there should be an infinite loop (if nothing is changing in another thread, as implied by unity docs). This is in Unity 3.5.

Why does it only work with the while loop? And why doesn't unity get stuck in an infinite loop?


texts: Should I use DirectX 11 for 2d games or should I stick to DirectX 9?

texts:
After two years now I wanted to continue working on my sandbox project which I actually used to learn and experiment with various C++ features and DirectX. So far I have simple elements for 2d adventures with a very basic engine, external map loading, scripts and this kind of stuff. So far the project was ported once from SDL to DirectX 9 and now I am considering to move on to DirectX 11 and the question would be: should I consider doing the step from DX9 to DX11 even though I am no going to make any 3d content at all?

Although often asked in various threads like this or this one which tech to use I couldn't find a suitable answer as people are referring to 3d rather than 2d.


texts: Performance of static const variable in shader

texts:
I am using static const variables based on uniform variables. For example:

uniform uint uSampleCount;

static const float invSampleCount = 1.0 / float(uSampleCount);

Is this static recalculated for every vertex and fragment, or are shader frameworks smart enough to initialize this once before the shader starts processing? Does using or not using static and/or const make a difference?


texts: Video playback in games - formats & decoding

texts:
What free / non-restrictive open-source solutions (not GPL) are available for decoding game videos?

The requirements are simple:

a relatively easy to use C API
encoded files must be quite small
there must be an application that converts videos from any format (whatever codec is installed on Windows or equivalent amount of internally decoded formats)
decoding has to happen fairly quickly
bonus points go to file formats that are popular / actively supported and
developed


texts: GLSL - std140 uniform block - fields(vec, float, mat4) always 0.0

texts:
Ok,

First of all, if just use uniforms everthing works like it should. Switching to uniform blocks nothing goes, as all values look like 0.0.  I tested this with various if-then-else stuff within the vertex shader and modifying the output color.

According to CodeXL 1.3(here the data is listed as VBO, but I think this is only cosmetic), GL.BindBuffer with GL.MapBuffer, or GL.GetBufferSubData there is really the proper data within my ubo but nonetheless the uniform block in the shader contains 0.0 only.

workflow:

    //Create UBO
    BufferUBOName = new int[2];
    GL.GenBuffers(2, BufferUBOName); // Generate the buffer
    BufferIndex = 0;

    GL.BindBuffer(BufferTarget.UniformBuffer, BufferUBOName[0]); // Bind the buffer for writing
    GL.BufferData(BufferTarget.UniformBuffer, (IntPtr)uboWorldData.SizeInBytes, IntPtr.Zero, BufferUsageHint.StreamDraw);  // Request the memory to be allocated
    GL.BindBufferRange(BufferRangeTarget.UniformBuffer, BufferIndex, BufferUBOName[0], IntPtr.Zero, (IntPtr)uboWorldData.SizeInBytes); // Bind the created Uniform Buffer to the Buffer Index

Creating and linking the shaders works fine and gives the following ouput :

GL   4.3
GLSL 4.30
Shader: basic_fs ok
Shader: basic_vs ok
ShaderProgram :hexgrid [ basic_vs, basic_fs ]
    Active Uniform Block : UboWorld
      Size         : 144
      BlockBinding : 1
      BufferPoint  : 0
        Name : UboWorld.time
          Type[n] : Float [4]
          Offset  : 0
        Name : UboWorld.screenwidth
          Type[n] : Int [4]
          Offset  : 4
        Name : UboWorld.screenheight
          Type[n] : Int [4]
          Offset  : 8
        Name : UboWorld.promat
          Type[n] : FloatMat4 [64]
          Offset  : 16
          matrix stride: 16
        Name : UboWorld.mvpmat
          Type[n] : FloatMat4 [64]
          Offset  : 80
          matrix stride: 16

    // Done after successful program linking
    uniformBlockIndices["ubodata"] = GL.GetUniformBlockIndex(shaderprog.Handle, "UboWorld"); // Gets the uniform variable Location
    if (uniformBlockIndices["ubodata"] != -1)
        GL.UniformBlockBinding(shaderprog.Handle, uniformBlockIndices["ubodata"], BufferUBOName[0]);

Then VBO / VAO are created and working fine, incl. drawing elements.

On UpdateFrame the UBO data will be processed like:

    GL.BindBuffer(BufferTarget.UniformBuffer, BufferUBOName[0]);
    GL.BufferSubData(BufferTarget.UniformBuffer, IntPtr.Zero, (IntPtr)uboWorldData.SizeInBytes, ref uboWorld);

The offsets are taken from the information after program linking and reading the various values for the UniformBlockActiveUniforms. I skip the output here as the struct should reflect it properly.

    [StructLayout(LayoutKind.Explicit)]
    struct uboWorldData
    {
        [FieldOffset(0)]
        public float time;
        [FieldOffset(4)]
        public Int32 screenwidth;
        [FieldOffset(8)]
        public Int32 screenheight;
        [FieldOffset(16)]
        public Matrix4 projectionMatrix;
        [FieldOffset(80)]
        public Matrix4 modelviewMatrix;

        public static readonly int SizeInBytes = 144;
    };

Vertex shader for testing:

    #version 400
    in vec3 in_position;
    in vec3 in_normal;
    out vec3 normal;
    out vec3 colortime;
    out vec3 colortimeubo;

    // These uniforms work
    uniform mat4 mvpmat;
    uniform mat4 promat;
    uniform float time;

    // This compiles fine. But always 0.0
    layout(std140) uniform UboWorld {
        float time;
        int screenwidth;
        int screenheight;
        mat4 promat;
        mat4 mvpmat;
    } w;

    const float pi = 3.1415;

    void main()
    {
      // This uses the UNIFORM FLOAT
      colortime = vec3(abs(sin(time * 360.0 * pi / 180.0)), 0.3, 0.3);
      // Here the uniform UboWorld
      colortimeubo = vec3(abs(sin(w.time * 360.0 * pi / 180.0)), 0.3, 0.3);

      normal = (mvpmat * vec4(in_normal, 0)).xyz;
      gl_Position = promat * mvpmat * vec4(in_position, 1);
    }

Any hints why w.time and also w.mvpmat or w.promat are always zero filled ???


texts:
I have some code that loops through a set of objects and renders instances of those objects. The list of objects that needs to be rendered is stored as a std::map>, where an object of class MeshResource contains the vertices and indices with the actual data, and an object of classMeshRenderer defines the point in space the mesh is to be rendered at.

My rendering code is as follows:

glDisable(GL_BLEND);
    glEnable(GL_CULL_FACE);
    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    for (std::map<MeshResource*, std::vector<MeshRenderer*> >::iterator it = renderables.begin(); it != renderables.end(); it++)
    {
        it->first->setupBeforeRendering();
        cout << "<";
        for (unsigned long i =0; i < it->second.size(); i++)
        {
            //Pass in an identity matrix to the vertex shader- used here only for debugging purposes; the real code correctly inputs any matrix.
            uniformizeModelMatrix(Matrix4::IDENTITY);
            /**
             * StartHere fix rendering problem.
             * Ruled out:
             *  Vertex buffers correctly.
             *  Index buffers correctly.
             *  Matrices correct?
             */
            it->first->render();
        }
        it->first->cleanupAfterRendering();
    }

    geometryPassShader->disable();
    glDepthMask(GL_FALSE);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);

The function in MeshResource that handles setting up the uniforms is as follows:

void MeshResource::setupBeforeRendering()
{
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);
    glEnableVertexAttribArray(3);
    glEnableVertexAttribArray(4);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); // Vertex position
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 12); // Vertex normal
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 24); // UV layer 0
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 32); // Vertex color
    glVertexAttribPointer(4, 1, GL_UNSIGNED_SHORT, GL_FALSE, sizeof(Vertex), (const GLvoid*) 44); //Material index
}

The code that renders the object is this:

void MeshResource::render()
{
    glDrawElements(GL_TRIANGLES, geometry->numIndices, GL_UNSIGNED_SHORT, 0);
}

And the code that cleans up is this:

void MeshResource::cleanupAfterRendering()
{
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    glDisableVertexAttribArray(4);
}

The end result of this is that I get a black screen, although the end of my rendering pipeline after the rendering code (essentially just drawing axes and lines on the screen) works properly, so I'm fairly sure it's not an issue with the passing of uniforms. If, however, I change the code slightly so that the rendering code calls the setup immediately before rendering, like so:

void MeshResource::render()
{
    setupBeforeRendering();
    glDrawElements(GL_TRIANGLES, geometry->numIndices, GL_UNSIGNED_SHORT, 0);
}

The program works as desired. I don't want to have to do this, though, as my aim is to set up vertex, material, etc. data once per object type and then render each instance updating only the transformation information.

The uniformizeModelMatrix works as follows:

void RenderManager::uniformizeModelMatrix(Matrix4 matrix)
{
    glBindBuffer(GL_UNIFORM_BUFFER, globalMatrixUBOID);
    glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(Matrix4), matrix.ptr());
    glBindBuffer(GL_UNIFORM_BUFFER, 0);
}


texts: organizing animation in Flash CS6 for sprite sheets

texts:
Can I make a sprite sheet of a character which contains animated movies inside the main movie-symbol?
I tried to export it, but those movies inside the main one are not animated.
Thanks


texts: Rotate relative to set point in a specified direction in a 3D space

texts: I know there's a geometry formula to calculate the next point in rotation relative to another point in 2D but I'm working in 3D and I want to calculate the next position in specified direction as well. Think Spiderman or the Bloodstalkers from ARK. I'm working in a game engine that uses the basic {x = 1, y = 2, z = 1} for vectors. I'm pretty bad at math so I honestly can't figure this out myself.


texts:
Does a basic/research RTS engine/model exist that can be used as a basis for further experimentation/research? I'd like to avoid reinventing the wheel if possible.
I'm aware of Spring Engine and Stratagus, but those are real game engines and may not be the best to experiment with and learn from.
Ideally the docs for the model would answer questions like:

How exactly do units move? (constant velocity? constant acceleration? constant force?)
How is pathfinding handled? Does every grid cell become an A* graph node (may be expensive)? Does it consider threats?
How are groups handled? (w.r.t pathfinding and movement)
How is combat handled?

I'm mostly interested in the low-level model details (for now), not the graphics etc.
I've read a lot of the other quesions (and answers/references) tagged RTS but I haven't found my answer yet.


texts: Do the lookDirection vector and upVector have to be orthogonal? What happens if they are not?

texts:
I'm currently starting with DirectX and building a small framework for myself and ran into a problem comprehending the camera vectors (position, lookDir, up).

What they represent exactly is clear, but here's the problem:

For my understanding the lookDirection Vector and the up Vector have to be orthogonal to each other. It this true? What happens if they are not?


texts: How to remove seams from a tile map in 3D?

texts:
I am using my OpenGL custom engine to render a tilemap made with Tiled, using a well spread tileset from the web. There is nothing fancy going on. I load the TMX file from Tiled and generate vertex arrays and index arrays to render the tilemap. I am rendering this tilemap as a wall in my 3D world, meaning that I move around with a fly camera in my 3D world and at Z=0 there is a plane showing me my tiles. Everything is working correctly but I get ugly seems between the tiles.

I've tried orthographic and perspective cameras and with either I found particular sets of parameters for the projection and view matrices where the artifacts did not show, but otherwise they are there 99% of the time in multiple patterns, depending on the zoom and camera parameters like field of view.

Here's a screenshot of the artifact being shown: http://i.imgur.com/HNV1g4M.png
Here's the tileset I am using (which Tiled also uses and renders correctly): http://i.imgur.com/SjjHK4q.png

My tileset has no mipmaps and is set to GL_NEAREST and GL_CLAMP_TO_EDGE values. I've looked around many articles in the internet and nothing helped.

I tried uv correction so the uv fall at half of the texel, rather than the end of the texel to prevent interpolating with the neighbour value(which is transparency). I tried debugging with my geometry and I verified that with no texture and a random color in each tile, I don't seem to see any seams. All vertices have integer coordinates, i.e, the first tile is a quad from (0,0) to (1,1) and so on. Tried adding a little offset both to the UV and to the vertices to see if the gaps cease to exist. Disabled multisampling too. Nothing fixed it so far.

Thanks.


texts: What are the best practices when colaborating with an audio engineer?

texts:
I am talking with various audio engineers and each has pretty much their own rates and way of colaborating. Since I am pretty foreign to their world and work process, I want to have a healthy relationship, and a fair money/work exchange.

Thus I want to inquire on the copyright use of the music. Naturally, the first would be the right to use all the sountracks in the game, for trailers, promotional material, conventions.

Secondary, I am thinking explicit permission for streamers and youtubers & the like to use the music for their edited videos and as background music while playing or streaming, as long as they give credit and link to the website or game page.

Thirdly, the right to sell the music, as an addon, on the game page.

Different sound engineers expressed explicit fobidding the second and/or third bulletpoint, and I am sure there is a fourth and fith, sixth...etc. that I am missing. So my question is a bit more complex.

I am open to suggestions on improving my question, perhaps I failed to get the message through.


texts: Secure login for a game that is open source

texts:
I am making a game which i will be open sourcing. Its a simple arcade like game but requires a network connection because it is meant to be played with other people.

The thing i am worrying about is how would i be sure that the client is the one that i put out for the end user to play with? Kind of a like of sv_pure for Team Fortress 2.

I was thinking of different ways to combat this such as the server requesting the client's version or even it's md5 hash but people with simple java knowledge could just force a method to always return what the server wants.


texts: Unintentional slight arm position change

texts:
In the scene I have a capsule with a camera parented and a looking script so when I look down or up the weapon slightly moves forward and then moves back when I look straight forward.

weapon when I look up or down-

and heres how it looks normally when I look straight forward-

Anyone knows how I can fix that?

EDIT: Here's how it looks in scene view


texts: Best way to do discontinuous animation? Or: Best way to animate a character with a jerky center of mass?

texts:
I am using Unity and need to know how to use it animation system properly for… well let me describe it below.

In this game I have this big 3D block-like character that moves in an unusual fashion compared to most game characters. In most games, the character moves along a straight line at a constant rate. However this character, and other characters in the game, does not move in a continuous fashion. Instead it is discontinuous and choppy in unique ways.

For example, here is how I want a big block character to move:

Basically the two corners in front of him are pivot points, and the character moves forward by alternating between these two points and rotating. How can I do this with Unity's animation system? For the most part the animations in Unity don't move the character but instead have an animation play, such as the "Run" animation, and then a script actually moves the character. Know I the animator has a “use root movement” or something that does exactly this, but I have heard that it can causes problems. I’ve been considering just programming all of the animations, since they are relatively simple. However that makes fine tuning them a nuisance, and have some animations programmed and others not is probably not a good practice. I kind of also fear that if I don’t end up programming it I will have troubles with detecting if a character can walk through a certain walkway, considering for example the above animation his “walk width” is greater than his actual width since he rotates side to side.

Also keep in mind that there are other animations that are discontinuous like this but work in different ways. For example, another block that hops but pauses between hops. Another might rock backwards and then slide forward on the forward rocking animation.

So I know there are multiple ways to tackle this, but my question is what is the best way to do this? How would you do it?


texts: Mip Maps on 2D Sprite causing black line above. Why is this?

texts:
I am new to Unity. I'm trying it out and using Futile for a code-first approach, but still importing textures using the Unity system.

The problem I'm having is that when I use mip maps to scale large sprites down to smaller sizes without jagged edges, I'm getting a black line artefact above said sprites.

A little hard to see, but they're there. If I turn down the resolution, you can clearly see them:

These are my texture settings:

My question is, why are these black lines here? Is it a mistake I've made? Is it just a common side effect? How can I reduce these? Also, if this is the wrong approach, how can I use smooth sprites in a game with the ability for them to scale up smoothly?

Thanks!


texts:
How to cut part of the object if it is inside a specific area? like showed on attached image.

PS

Looks like stencil should be used, but I am not really sure how to do it.


texts: How do I correctly unload an additive Scene in WebGL?

texts:
I am creating an app in WebGL.  I have a loading scene that I am loading additively:

SceneManager.LoadScene("Loading Scene", LoadSceneMode.Additive);

It loads correctly.

Then after I finish loading everything, I remove the additive loading scene:

SceneManager.UnloadScene(SceneNames.Loading);

In the Editor, it unloads perfectly.  However, in browser, via WebGL, it gets called, but does not unload.  If I throw it in a coroutine and wait for 3 seconds, it does unload.

I have a two-part question:

Why does waiting for 3 seconds before unloading fix the problem?
What is the correct way to unload this scene so that there is not an arbitrary "Wait for seconds" in there?


texts:
Short Version:

I am trying to move a player around on a tilemap, keeping it centered on its tile, while smoothly controlling it with SneakyInput virtual Joystick. My movement is jumpy and hard to control. What's a good way to implement this?

Long Version:

I'm trying to get a tilemap based RPG "layer" working on top of cocos2d-iphone. I'm using SneakyInput as the input right now, but I've run into a bit of a snag.

Initially, I followed Steffen Itterheim's book and Ray Wenderlich's tutorial, and I got jumpy movement working. My player now moves from tile to tile, without any animation whatsoever.

So, I took it a step further. I changed my player.position to a CCMoveTo action. Combined with CCfollow, my player moves pretty smoothly. Here's the problem, though: Between each CCMoveTo, the movement stops, so there's a bit of a jumpiness introduced between movements.

To deal with that, I changed my CCmoveTo into a CCMoveBy, and instead of running it once, I decided to have it CCRepeatForever. My plan was to stop the repeating action whenever the player changed directions or released the d-pad.

However, when the movement stops, the player is not necessarily centered along the tiles, as it should be. To correctly position the player, I use a CCMoveTo and get the closest position that would put the player back into the proper position. This reintroduces an earlier problem of jumpiness between actions.

What is the correct way to implement a smooth joystick while smoothly animating the player and keeping it on the "grid" of tiles?

Edit:

It turns out that this was caused by a "Bug Fix" in the cocos2d engine.


texts:
So, I've got a fighting game with some pretty tight input windows, and I'd like to buffer the inputs for a few frames.

Basically, if the fighter is in the neutral state, pressing attack should lead into an attack. It uses Input.GetButtonDown("attack") to get the button, and if it detects a press, transitions into attacking state. Now, let's suppose the fighter has just landed, and ends up hitting "attack" a few frames before the land animation ends and he transitions back into neutral. As of right now, nothing would happen, since he's not in the neutral state where the check is, and when he enters the state, the button press is no longer happening.

Is there a way to store inputs for a few frames, so that I can read a button press a few frames back? So, instead of using Input.GetButtonDown("attack"), it'd be something like InputBuffer.KeyBuffered("attack",12) to see if the button was pressed within 12 frames?

The example above is just a bit of a simplification, I know for the above situation I could just use GetButton instead of GetButtonDown, but for a fighting game, you can imagine that the necessary inputs to buffer would get significantly more complicated.


texts: Calculating How To Intercept a Moving Object

texts:
So I have two objects, Target and Interceptor. Target's position, direction of movement and movement speed are known, and Interceptor's position and movement speed are also known. Both movement speeds are fixed, and Target will never change course. Both are moving in three dimensions; Interceptor can move in any direction.

I want to figure out which direction Interceptor needs to move in, at its fixed movement speed, to be able to collide with Target as Target moves, as quickly as possible - or, as the case may be, I want to know if it is impossible for Interceptor to collide with Target.

I don't know how to do this, and my Google searches clearly haven't been using the right search terms, because nothing useful comes up. How do I calculate this?


texts: How To Correctly Extend the Sprite Class in LibGDX

texts:
I am currently pursuing game development as a hobby, and have run into what seems to be a conflict in my mind regarding how to properly (using best practices) extend the Sprite class in LibGDX (or for the sake of this question, any Sprite class).

What I Would Like To Do

I would like to to create a class, Ship.java, with the constructor as follows:

// Note the lack of a Texture object in the constructor here
public Ship(float startingX, float startingY){

    super(new Texture(Gdx.files.internal("data/ship_texture.png")), 0, 0);

    this.startingX = startingX;
    this.startingY = startingY;

}

Why I Can't Do This

First, this implementation forces me to forfeit having a reference to the Texture that I am passing into the super constructor.  This means that I cannot properly dispose() it later, which would lead to memory leaks later in the code.

The Problem

Since the constructor of the Sprite class forces you to specify a Texture, and I would want a Ship to always have the same Texture (thus would not want to specify it in the constructor of a Ship), I am limited to hacking together some factory method to construct the Ship.

My Current Solution

As specified above, I currently have a factory method that creates the Ship instead of using the constructor.

The Code

Below I have detailed the code I am currently using to get the Ship class instantiated.  Please feel free to critique it:

// Private constructor because I do not want this method to be called ever
private Ship(Texture texture, int row, int column) {

    // Calls the super constructor (for the Sprite class)
    super(texture, row, column);
}

// Instead, this create method returns a new instance of Ship
public static Ship create(int row, int column){

    // Create the new texture
    Texture texture = new Texture(Gdx.files.internal("data/ship.png"));

    // Set the LINEAR filter (might switch to NEAREST later)
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    // Return a new instance of the Ship
    return new Ship(texture, row, column);
}

Why I Don't Like This Solution

I feel as though this is a very "hacky" fix, as it defeats the purpose of a constructor, and although static factory methods are good practice, I don't think it should be necessary to implement a new factory method for each object I plan to draw on the Screen.

My Question

What is the best way to extend the Sprite class (thus keeping all the helper methods that it provides), and still define the Texture that will be displayed on the object within the constructor of the Ship?

Is the current approach I am using appropriate?


texts: How can I convert an orthographic camera to a perspective camera?

texts:
How can calculate perspective camera parameters from orthographic camera parameters (left, right, top, bottom, near, far)?

Specifically I don't know how calculate the FOV for a perspective camera from orthographic camera.


texts: How to name HP/MP/Exp bars in a single word?

texts:
I have one question related to game design.

In my prototype game, I have an options when you can change look of your HPbar, MPbar and Expbar. Actually I don't know how to easily name this option.

Currently have "player HP/MP/Exp bars - Value", but it doesn't look so great.

I am looking for a simple name for this, so I want to provide more understandable naming for player.


texts: How should I arrange collision primitives around characters for a top-down, oblique game?

texts:
I'm planning to develop a top-down oblique mobile game (like the one in the screenshot below), but I'd like to understand something before I start:

When I'm working on collisions, where should the fixture for collision be? Should it be at the character's feet, or elsewhere?


texts: In my 2D tile-based game, I have NPCs that move around on a fixed path. I am putting the information about the NPCs in a .plist file that is loaded on startup. The thing is, I'm not sure how to format the data specifying the path that the NPC moves on. What I was thinking was to have an origin property, a horizontalMovement property, and a verticalMovement property, so when the starts at its origin, then walks right the number of tiles specified by horizontalMovement, then walks the number of tiles down specified in verticalMovement, etc. However, this doesn't seem like the best approach. Is there a better way to store the movement data?


texts:
Sorry for the bad title, if you think of a better one please tell me.

So I was asked to make a button that says a line from a video game. I attempted to have the while loop add 1 to a variable every time it looped through, then display the variable in the caption of the window. I did this so that I could see if it was looping, and really, what was going on. It showed a rapidly increasing number, then froze the computer (I had to restart the computer). I tried putting a short wait in the loop, still would not respond. I am also having this exact same problem in a much longer and more complex program that I'm working on, so if I figure it out, it will solve both issues. Don't just give me code, please tell me why I need to use it or what it does. Here's the program:

from pygame import *
import pygame
pygame.init()

pygame.display.set_caption('Potato')
screen = pygame.display.set_mode((224, 224))
button = pygame.image.load("C:/Python34/redbutton.jpg")
screen.blit(button,(0,0))
pygame.display.flip()

potato = pygame.mixer.Sound("C:/Python34/potato.wav")

test = 0
pressed = False

while pressed == False:
    if pygame.mouse.get_pressed()[1]:
        pressed = True

    if pygame.mouse.get_pressed()[0]:
        potato.play()

sys.exit()


texts: OpenGL: glGetError() returns invalid enum after call to glewInit()

texts:
I use GLEW and freeglut. For some reason, after a call to glewInit(), glGetError() returns error code 1280. Reinstalling the drivers didn't help. I tried to disable glewExperimental, it had no effect. Code worked before, but I am not aware of any changes I could possibly make.

Here's my code:

int main(int argc, char* argv[])
{
    GLenum GlewInitResult, res;

    InitWindow(argc, argv);

    res = glGetError(); // res = 0

    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    res = glGetError(); // res = 1280

    glutMainLoop();

    exit(EXIT_SUCCESS);
}

void InitWindow(int argc, char* argv[])
{
    glutInit(&argc, argv);

    glutInitContextVersion(4, 0);
    glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
    glutInitContextProfile(GLUT_CORE_PROFILE);

    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,
    GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    glutInitWindowPosition(0, 0);
    glutInitWindowSize(CurrentWidth, CurrentHeight);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);

    WindowHandle = glutCreateWindow(WINDOW_TITLE);

    GLenum errorCheckValue = glGetError();

    if (WindowHandle < 1)
    {
        fprintf(stderr, "ERROR: Could not create new rendering window.\n");
        exit(EXIT_FAILURE);
    }

    glutReshapeFunc(ResizeFunction);
    glutDisplayFunc(RenderFunction);
    glutIdleFunc(IdleFunction);
    glutTimerFunc(0, TimerFunction, 0);
    glutCloseFunc(Cleanup);
    glutKeyboardFunc(KeyboardFunction);
}

Could someone tell me what I am doing wrong? Thanks.


texts: LibGDX - Waiting for sound or music to finish

texts:
I understand that all sound playing in LibGDX happens asynchronously (for good reasons), however I'm now struggling to do something as simple as:

(Character dies)

Play a sound
When the sound has finished playing, play another sound
When the second sound has finished, display a button that has to be pressed for the game to start over

My code is as follows:

if (hasDied){
  dieSound.play();
  gameOverSound.play();
  showButton();
}

But what it does is, obviously, play the two sounds at the same time, while displaying the button. It's even possible for the user to press the button while the sounds are playing.

Now, I can put a check in the button listener to not do anything if dieSound.isPlaying() or gameOverSound.isPlaying(), but of course that does nothing to avoid concurrent playing of the two sounds and still displays the button before the sounds have finished playing. Now I see that Music objects, as opposite to Sounds, have a setOnCompletionListener() method, which could perhaps be (ab)used this way:

if (hasDied){

  gameOverMusicCompletionListener = new OnCompletionListener(){
    @Override
    public void onCompletion(Music a) {
       showButton();
    }
  }

  dieMusicCompletionListener = new OnCompletionListener(){
    @Override
    public void onCompletion(Music a) {
       gameOverMusic.setOnCompletionListener(gameOverMusicCompletionListener);
       gameOverMusic.play();
    }
  }

  dieMusic.setOnCompletionListener(dieMusicCompletionListener);
  dieMusic.play();
}

This looks quite kludgy to me, isn't there another way to accomplish what I'd like?


texts: Reduce bounciness of dynamic bodies in Box2D

texts:
In my 2D platformer game my player character is modeled using a Box2D dynamic body. One thing I thought feels off though is that even though the restitution of the fixture applied is zero, the player will bounce off static geometry when falling at an angle, kind of like a plastic box would perhaps, but certainly not like a body would.

There isn't really much that Box2D allows me to tweak though except for density and restitution? I noticed that playing with the density has basically no effect on how the player moves which I thought was odd too.

Are there any realistic value ranges you would recommend? It's all a bit trial and error right now for me.


texts:
I'm in pre-production on a strategy game and am trying to determine if the core gameplay will be fun. A good technique to determine this is to strip the game down to its minimum viable product (MVP) and see if that is fun. If the MVP isn't fun, then no amount of extra content or features will make it fun.

I'm having difficulty determining the MVP for a strategy game as I'm a little too far into the weeds to see which of the many design features are core mechanics and which are unnecessary.

Purely as an example, lets just say StarCraft2 is the strategy game I want to make. What would be the MVP for SC2 to prove out that its core gameplay is fun?


texts: How can I get textures to combine naturally in Half Life SDK?

texts:
I'm quite new to Half Life SDK, the SDK dedicated to the original Half Life, and have mostly been testing my abilities by recreating certain scenes from Half Life 1 and its expansions.

One such scene is the starting room of Half Life: Opposing Force. It was going great until I reached the simple (or so I thought) desk. Image below.

The desk in the game looks to be one unbreaking texture going around a corner without any pattern break too noticeable.

After resizing, repositioning, and doing other similar things to the textures I arrived at my current progress below after I made several rectangles with each one alternating by flipping the texture to try to get a smooth infinite loop of just part of the texture.

It repeats in the dark gray area on the right.

I have arrived at a mental dead end when it comes to how to get the corner to look natural and, while the repeat in the dark gray area is harder to notice, it is still noticeable and is made extra noticeable when there are bullet holes or blast marks on one of the creases.

So to sum up my question: How can I get my textures to appear unbreaking in a similar fashion to the game in Half Life SDK?


texts: How can I synchronize state in my Asteroids game with many networked players?

texts:
Wondering how state synchronization works in games with lots of players like MMOs. It seems like a hard problem to solve and I am not aware if there are standard solutions. Specifically, synchronizing game clients (users playing game) with an array of centralized servers, and then broadcasting and merging the state with all the same connected clients. How it is done (and how efficiencies are implemented) typically, and what the structure of the game state is like.

To simplify this question, I am thinking in terms of a simple asteroids game:

You have n number of players, and the asteroids, players, and bullets are synchronized across clients. I am not familiar with how the game state should be modeled (if it's some quadtree thing you are sending around, or just a vector of patch/updates, etc.). There could be players all over the world, so latency is a factor.


texts:
I have a problem with stretching sprites in LibGDX.

I have one png file for the sky in the game (1 x 1000px) and I want to render it 1000 x 1000px

sprite.setSize(pixelWidth,pixelHeight);

I want to stretch this 1px-wide sky image. It has little gradient from the top to the bottom, as you can see. I want to make it 1000px in width. But I get this strange result:

You can see that there is something like a horizontal gradient, even with lines, but there's no apparent reason why that's happening, since I'm scaling a 1px wide image!

The strange thing is that everything looks fine on other PCs and mobile phones - but I don't think that the problem is with my PC!?

I don't know what to try. Any ideas?


texts:
I am creating a model pack for a game and I am having a hard time deciding how many sides I should start with for the low poly props made from cylinders and spheres.

Take an apple for example. I want to maintain the apparent roundness of the shape at a glance but keep the polygon count low. The model pack is household clutter so there could easily be 50 such objects to render at any time.

What is a decent polygon count for minimal spherical objects?


texts: Can a character interact well with surroundings in-game?

texts:
I don't have any experience in game programming, but I am currently on programming-related degree, although on a different branch to game design.

I thought about how an environment can come more alive with player movement. For example, currently in many games once you hit a wall you would continue walking into that wall in one spot. I wanted to know, if there is a possibility to make interaction instead, etc. program a certain way to push towards the wall and listen, or lean against the wall, depending on joystick feedback. I wanted to push this even further to how player interacts with an object. For example, walking into a chair wouldn't just make the character be stuck on walking into the chair, but also make certain interactions like a strong fall if player runs into it and make the body of the player respond to what's happening as well. A further example would be placing something heavy on a chair for example, like a rock, and then if a player tries to push it requires more force which builds up, makes the chair make heavier sounds, and have the rock slightly rocking with the force.

Is this at all feasible in gaming and doable for a project? I have no experience in games, so it is hard to say what can be realised with today's tools like Unity or Unreal Engine.


texts:
A few questions on the site have mentioned the need for more open source projects. I agree and wonder what frameworks should be developed.

I'll start the list.

A geometry kernel, including
serialization (JSON, binary,
compressed binary), tailored for
OpenGL/DirectX
Gesture recognition


texts: How can I profile the speed of my vertex and fragment shaders separately?

texts:
I'd like to know how I can check to see if either my vertex or my fragment shader is a bottleneck in my rendering pipeline.

I've read about using glQueryCounter with the GL_TIMESTAMP target to get clock checkpoints between OpenGL commands, but these don't distinguish between different types of shaders.

For example, if one frame on the GPU took 8 ms to render, can I tell that the vertex shader took 7 ms and the fragment shader took 1 ms?


texts: Handling Background & other objects in a Flash platformer

texts:
I asked a similar question in 'SO' not knowing about this place,anyways here goes:

I wanted to know what the best approaches are while creating a platformer based game for handling background & objects.

Tiled method - Using small objects & loading on-the-fly :
I understand this is good for employing a level editor for the game later but wouldn't it become too processor intensive to manage so many tiles(using arrays, i assume). Especially if have many objects which also might be mutually exclusive (eg different sets of bg objects which react differently to user). Please throw some light on what usually the tile sizes often considered. I have a doubt that I used too small tiles which reduced my frame rate drastically.

Create, store & scale:
Creating the whole level & storing them in separate movie clips, scaling them while the level loads. I found this method could solve the frame rate problem, but I then had to handle the issue of not  being able to place objects (like enemy, power ups, etc) during runtime, as I no longer tracked the exact locations of the player (hero) in the game.


texts: Lighting large scene with dynamic lights - Unity3D

texts:
I am working on a game project where most of the action takes place in a large scene that is built to look like a space station. Because it is all technological and enclosed, I can't use a directional light to light the whole scene, and I need to be able to change the color of the lights for an alarm system. I can't bake the lights, because then I can't change their color, and I can't leave them all as dynamic lights, because I have about fifty spot-lights, and they take up a huge amount of memory, so much so that the lights can't even render on mobile devices.

Is there any way to do this without baking?

I am getting about 3000 batches in the Unity Editor Stats on average, in some places it is higher. Even viewing the game in full screen in the editor makes the game run super slow because of the amount of rendering it has to do, and I have a pretty new computer.

Here's a picture of my scene (As you can see, it is fairly large as you are able to see the UI box clearly from the scene editor):

And here's the Stats box:

Here is an example of my scene in play mode:

UPDATE:
I removed the shadow casting, which isn't necessary for my project, and it improved the framerate slightly, and the batches number is smaller, averaging out at about 1500 now, but the performance still is not optimal.


texts: How can I spin a child capsule of a cube parent?

texts:
I have a parent cube and to make it like a surface I had to change the rotation of the cube on the X to 90. and as a child, I added a capsule, and to make the capsule-like standing I had to change the capsule X also to 90. The result is :
The reason I put the capsule child of the cube is that I want the capsule to move with the cube.

The capsule rotation on the X is also 90 :

Then in a script at the top, I added speed and index variables for the rotation :
private int index = 0;
private int rotationIndex = 0;

In the Update :
RotateTo();

And the method : curvedLinePoints is a List
private void RotateTo()
    {
        var distance = Vector3.Distance(capsule.position, curvedLinePoints[rotationIndex].transform.position);
        if(distance < 0.1f)
        {
            rotationIndex++;
        }

        // Determine which direction to rotate towards
        Vector3 targetDirection = curvedLinePoints[rotationIndex].transform.position -capsule.position;

        // The step size is equal to speed times frame time.
        float singleStep = rotationSpeed * Time.deltaTime;

        // Rotate the forward vector towards the target direction by one step
        Vector3 newDirection = Vector3.RotateTowards(capsule.forward, targetDirection, singleStep, 0.0f);

        // Draw a ray pointing at our target in
        Debug.DrawRay(capsule.position, newDirection, Color.red);

        // Calculate a rotation a step closer to the target and applies rotation to this object
        capsule.rotation = Quaternion.LookRotation(newDirection);
    }

The problem is that because the capsule is a child when I rotate the capsule it looks like the capsule changes its shape and not spinning around itself. If I remove ut the capsule from the prefab and will rotate it on its own it will spin fine but when it's a child of the cube the result is :

I tried before running the game to play with the capsule rotation in the editor in the inspector changing the Y and Z values and the result is like in this screenshot. but I want to spin it around itself but because it's a child of the cube it's not spinning but looks like it's changing its shape.
The workaround I found is to create an empty GameObject at 0,0,0 and put both Platform and Capsule as a child of it.
Then I added this part to the script above :
private void LateUpdate()
    {
        capsule.localPosition = transform.localPosition + new Vector3(0, 1.4f, 0);
    }

This way the Capsule is following the Platform. The empty GameObject is just to put them both together.
and for testing I just did in the Update :
capsule.Rotate(0, 10, 0);

and it's working fine. Now I have to figure out how to make this rotation with the code in the RotateTo method.


texts: Determine facing direction mecanim 2d movement

texts:
I'm using this script to move my character in my 2d world:

    public float speed;   //Movementspeed

public Rigidbody2D rbody;
Animator anim;

void Start () {

    rbody = GetComponentInChildren<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
}

void FixedUpdate () {

    Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (movement_vector != Vector2.zero) {
        anim.SetBool("iswalking", true);
        anim.SetFloat("input_x", movement_vector.x);
        anim.SetFloat("input_y", movement_vector.y);
    } else {
        anim.SetBool("iswalking", false);
    }

    rbody.MovePosition (rbody.position + movement_vector * speed * Time.deltaTime);

}

}

What I want is to somehow register where my character is facing/walking towards to be able to Instansiate a gameobject infront of it.

How do I do that?


texts:
So I'm trying to solve a heat/diffusion equation for a continuous space, but I'm not opposed to a grid solution. I'm a little short on the maths needed but have made it work so far.

If I model sources and sinks on a grid, I just need to center a gaussian potential on that coordinate with the appropriate sign. A source is like a positive metaball and a sink is like a negative one. Similarily, I can just do a gaussian blur of the entire image if it has no walls. The sources and sinks will smear together and give the actual solution.

However, if I have walls I can't do that, because there are boundary conditions to the problem all of a sudden. I could incrementally blur by a small amount, then add the walls back in, but I'm looking for a solution that I can lookup any t (time) for directly.

I could also expand the heat map out from sources and sinks by flood filling from those points, but I need the heat value to be implicitly there. I'll be pulling single values of perlin noise out of the air for obstacles and don't want to evaluate the entire field only to pull a single heat value.

So, is there any way I can define the boundary conditions as part of the convolution (gaussian blur) using math or some technique?

I looked at potential fields but I don't think that solves the diffusion exactly. To restate, how do I add boundaries to a diffusion problem and solve for a specific coordinate (x,y,t)? It should be possible since the boundary/obstacle is a single function f(x,y,t).


texts: Can Google App Engine communicate with a stand alone program?

texts: If I create a client program using say C#, or develop something for the Android or Iphone, can I use Google App Engine for the server and communicate with the client application mentioned above?


texts: How can I expose material parameters in the Unreal level editor?

texts:
Is there a way to expose material parameters in Unreal 4 so that they are accessible from the level editor?

As far as I know, I can only do this through the Material Editor, but I wish to do it more fluently.

E.g. to edit a color for the currently selected object in a level:


texts: optimizing collision detection with stationary objects (walls, floors, obstacles, etc.)

texts:
For detecting collisions between sprites, I know a 2D spatial hash is a way to optimize the number of collision checks that need to happen. But is there a way to optimize even further for objects that we know won't be moving in the scene? My sensibilities tell me that there should be because:

We know exactly where the object is at all times.
(At least in my game) there are bound to be a lot of floor/wall/ceiling tiles, far more than would be efficient to include in the spatial hash.

So, is there a way to optimize collision detection for this use case?


texts:
I've been reading valve's article on multiplayer networking repeatedly recently and everything is starting to make since. One thing I'm wondering on though however is what percentage value to use for interpolation. For example the article shows this image:

Then the following explanation is given:

  The last snapshot received on the client was at tick 344 or 10.30 seconds. The client time continues to increase based on this snapshot and the client frame rate. If a new video frame is rendered, the rendering time is the current client time 10.32 minus the view interpolation delay of 0.1 seconds. This would be 10.22 in our example and all entities and their animations are interpolated using the correct fraction between snapshot 340 and 342.

At the end of the last sentence it states to use "the correct fraction between snapshot 340 and 342". What would this fraction be? Is it the time it takes for a frame to render?...or am I way off?


texts:
I'm curious to know the workflow when creating a game in Unity3D?

Does it generate a lot of code for you?

My understanding is that you describe the game in Unity and do scripting on the back end to do the logic. Kind of like you use Unity to describe the puppets and you use a scripting language as the puppet master.


texts: How do I split my screen to include a JFrame and a lwjgl screen

texts:
I a making a game and I'm going to make a little side GUI to create game items.

How can I have a window both include a Canvas element and an lwjgl window.


texts: Why does my material look blotchy on this mesh?

texts:
This is a generative mesh - wireframe looks like this

Here's the material

But the shaded object looks like a tie dye tshirt

I've no idea what settings are causing it to look like this. These are the settings of the mesh renderer


texts:
I'm dealing with Slopes in a 2D platformer game I'm developing in XNA Game Studio. I was really tired of trying without success, until I found this post: 45° Slopes in a Tile based 2D platformer, and I solved part of the problem with the bummzack answer.

Now I'm dealing with 2 more problems:

1) Inverted slopes:

The post says:

If you're only dealing with 45 degree angles, then it gets even simpler:

y1 = y + (x1 - x)

If the slope is the other way round, it's:

y1 = y + (v - (x1 - x))

My question is, what if I'm dealing with slopes with less than 45 degree angles? Does y1 = y + (v - (x1 - x)) work?

2) Going down the slope:

I can't find a better way to handle the "going down through the slope" situation, considering that my player can accelerate its velocity.

Edit: I was about to post a image but I guess I need to have more reputation he he he... What I'm trying to say with "going down" is like walking towards the opposite direction, assuming that if you are walking to the right, you are incrementing your Y position because you are climbing the slope, but if you are walking to the left, you are decrementing your Y position.


texts: Android opengles 2.0 :different resolutions rendering and input

texts:
I'm currently developing a sprite based 2D game for android using opengles 2.0. I've got some basic rendering done that mimics the spritebatch functionality of xna (draw sprite, rotation, color). But all of this works for a fixed projection matrix, but android has a lot of screen sizes.

Q1)Would this be an okay method to scale up/down the drawing?

1)Draw the whole screen to a texture.
2)Draw the above texture as a quad to the device.

I found the above through some searching, not sure if it's the best one, are there any alternatives?

Q2)How do you handle inputs for different resolutions? I currently get the position of a touch and use it raw. Would it be okay to get the position, and then scale the position to size of the texture used for rendering, and the perform calculations on it?

Thanks.


texts:
I recently added a texture packager to my project that will pack a certain amount of textures into a single one, like this:

So for example this one is 582x1023 pixels in size. The goal of adding these packed textures was obviously to improve performance so I wanted to look up the optimal texture size for OpenGL (using LWJGL) textures. The things I found were that a widely supported maximum texture size seems to be 1024x1024, according to this for example. This strikes me as odd because obviously a lot of textures alone would be larger than that, so what happens with those? I am pretty sure most graphics cards support textures bigger than that. Can I reasonably expect most graphics cards to handle e.g. 4096x4096 textures (or maybe even larger than that)?

To come to my second point (I hope this still counts as one question, but it essentially boils down to the same issue): Should textures be sized to a power of 2 (256x256, 512x512, 1024x1024, 2048x2048, ..) and should I pad packed textures smaller than that to the next power of 2? According to this question from 2011 it is not a requirement but can improve performance and avoid minor bugs and this one from 2012 says that you definitely should pad textures. So I realize that these questions have been asked before but they are reasonably dated for the answers to have changed and further they each only partially answer my question. How do other projects / handle this?

TL;DR: What textures sizes can I expect most graphics cards to handle? What are the optimal texture sizes (or are there)? Should I pad textures width to the next power of 2?


texts: Unity animation editor having trouble to animate twice the same component

texts:
I'm not getting warm with the Unity animation editor.

This is what I want to do:

The 2 lasers should be like this, rotating 360 degrees over and over. .The classname laser2 doesn't mean anything, I implemented 2 concepts therefore this is the laser2 class.
However, the animation editor seems to have a problem with having the same component more than once. I'm only able to animate the first laser.

As soon as I open the Laser2 section, it opens both lasers and changes in it are only stored in the first laser. Is there way to make them seperate? Having the exact same class twice (with different name) will help but that's an unbelievable dirty solution.
I did not do much with the animation editor so far so maybe there is some easy fix that.
Edit: Startangle is the value which must be animated on both.


texts: WebGL rendering performance and frustum culling

texts:
When I render five boxes in WebGL with one texture for all of them, the app runs at 60 FPS, nice. But when I render 70 boxes the performance decreases to ~40fps... but only 5 of the boxes are visible.

I have debugged the app and all 70 boxes are using per fragment shaders when there is no need because 65 of them are out of frustum. I thought that setting the GL viewport clipped out-of-view polygons, but apparently not.

I would like to know if I can use frustum culling techniques to avoid this? How can I activate frustum culling? Is there any WebGL command or I have to do it manually?

Thanks in advance,


texts: How do I access variables in the Game1 class from another class in XNA?

texts:
I'm trying to write a SpriteManager class in XNA, but I need access to the Game variables. For example, the Game.Content property would be very helpful in loading textures, and Game.GraphicsDevice.Viewport would be helpful in getting the window size.

For now, I have the following class:

public MainGame : DrawableGameComponent
{
    public SpriteManager<Enemy> EnemyManager { get; get; }
    public SpriteManager<Powerup> PowerupManager { get; set; }
    ...
}

I can think of three ways of getting access to these variables in the SpriteManager class:

Make my sprite manager class derive off of GameComponent. This would be ideal, except that my sprite manager is used in MainGame, which is a GameComponent.
Use ((Game) Game1) to access the variables. However, doing this kind of cast is ugly and breaks encapsulation.
Pass everything down from MainGame. For example, EnemyManager needs to load a random enemy type each time it spawns an enemy, so instead of loading the textures in MainGame, pass EnemyManager the Game.Content property and let it handle texture loading. However, I'm not sure if this is the best way of handling the situation. I can't place my finger on it, but it just seems 'wrong'  in some way.

I could use some advice on the best way of achieving this.