texts: Styles of games that work at low-resolution

texts:
I'm taking a class on compilers, and the goal is to write a compiler for Meggy Jr devices (Arduino). The goal is just to make a simple compilers with loops and variables and stuff.

Obviously, that's lame, so the "real goal" is to make an impressive game on the device. The problem is that it only has 64 pixels to work with (technically 72, but the top 8 are single-color and not part of the main display, so they're really only useful for displaying things like money).

My problem is thinking of something to do on a device that small. It doesn't really matter if it's original, but it can't be something that's already available. My first idea was "snake", but that comes with the SDK. Same with a side-scrolling shooter.

Remaining ideas include a tower defense game (hard to write, hard to control), an RPG (same), tetris (lame)..

The problem is that all of the games I like require a high-resolution screen because they have a lot of text. Even a really simple game like nethack would be hard because each creature would be a single color.

tl;dr What styles of games require a. No text; and b. Few enough objects that representing them each with a single color is acceptable?

EDIT: To clarify, the display is 8x8 for a total of 64 pixels, not 64x64.


texts: Distance between two lines (textbook answer vs practical application)

texts:
I'm reading through "Mathematics for 3D Game Programming, and Computer Graphics" as a refresher, and leading in to some more complex real world problems down the line. However, one of the early chapters has a bit of math that seems overly complicated. This question deals with a problem from the textbook, that I believe the solution is far simpler than their recommended one.

The problem is to find the distance between two lines (in 2 or 3 dimensions).

Some set up:

1) Lines are set up parametrically as opposed to two points.

Line 1:

Line 2:

Where P = S + tV -- S is the starting point (say, A) and equals (1-t) * A

Now the book states to use this solution :

Expanded looks like:

Then the books next step is to reduce this, and take the derivatives with respect to time for both

 and

Once the derivatives have been calculated. We move to a matrix form, and solve using some linear algebra.

My question is this, why would I use that series of steps when I already know the [ x, y, z ] for both points using the parametric. With those values wouldn't the simpler solution be just to do:

Then:

Finally:

Is there some direct application of the former equations that I am missing (the book does not elaborate currently on its applications here)? I've had some discussion with other game developers, and we haven't found much a use case for the linear algebra set up.

Edit: (The linear algebra solution)

First both derivatives with respect to time:

Then in matrix form, solve for both t variables:


texts: How to balance experience gain with player collaboration?

texts:
I'm developing an online game with friends, and we're currently blocked by a overall game design issue: how do you reward players with experience points and loot/gold yet still encourage them to play together, especially with players who are not necessarily in their skill range?

Technical details of our game:

Grid-based, top-down overworld map layout (think Legend of Zelda)
Randomly generated, turn-based dungeons (think Pokemon Mystery Dungeon)
Experience curves, non-combat skills, trading, social interaction (think Runescape)

The plan is for players to socialize, do parts of quests, and skill in the overworld, then enter dungeons with groups of ~4 friends into order to skill combat and get loot. Ideally, more skilled players can enter harder dungeons and do harder tasks, yet still be able to join newer players in easier dungeons without it being mundane and without forcing one player to take up most of the combat.

Possible fixes:

Remove all sorts of experience curves and rewards, and have everything be balanced (downside: no reason to grind)
Restrict "leveling" to gaining more money and better weapons (downside: having more loot virtually becomes being a higher level)
Raise low-leveled players to the level of the highest-leveled team member when in dungeons (downside: may be a loophole to allow players to skill quickly)
Add an extra component of the game that requires user skill, so players won't rely solely on levels to be good at the game (e.g. quick time events) (downside: hard to implement in a turn-based game, ambiguous)

These are just some ideas, and I have been pondering this issue for a little while now. What are some thoughts on this issue and what mechanic may be introduced to reconcile this?


texts: Artifacts at seams between meshes in Unity in isometric camera only

texts:
I'm trying to piece together some very simple placeholder models that I intend to use as tiles in Unity and I'm seeing odd pixel artifacts along the seams of the tiles that only show up when using an isometric camera. You can see them in this image.

And the same geometry but just from a perspective camera shows no artifacts.

I verified that the two models are exactly aligned right along the seam by checking the actual vertex data. The artifacts are dependent on the camera itself and shift along the seam as the camera is panned and zoomed.

I've disabled shadows, set the texture filter mode to point, disabled mipmap generation

The geometry is quite simple and is imported from the OBJ file below.

# normals
vn -1 0 0
vn 1 0 0
vn 0 0 1
vn 0 0 -1
vn 0 -1 0
vn 0 1 0

# texcoords
vt 0.970703 0.5
vt 0.974609 0.5

# verts
v 0 2 0
v 0 2 -4
v 0 2.3 0
v 0 2.3 -4
v 0 2.5 0
v 0 2.5 -4
v 4 2 0
v 4 2 -4
v 4 2.3 0
v 4 2.3 -4
v 4 2.5 0
v 4 2.5 -4

# faces
f 3/2/1 2/2/1 1/2/1
f 4/2/1 2/2/1 3/2/1
f 5/1/1 4/1/1 3/1/1
f 6/1/1 4/1/1 5/1/1
f 7/2/2 8/2/2 9/2/2
f 9/2/2 8/2/2 10/2/2
f 9/1/2 10/1/2 11/1/2
f 11/1/2 10/1/2 12/1/2
f 7/2/3 3/2/3 1/2/3
f 9/1/3 5/1/3 3/1/3
f 9/2/3 3/2/3 7/2/3
f 11/1/3 5/1/3 9/1/3
f 2/2/4 4/2/4 8/2/4
f 4/1/4 6/1/4 10/1/4
f 8/2/4 4/2/4 10/2/4
f 10/1/4 6/1/4 12/1/4
f 2/2/5 7/2/5 1/2/5
f 8/2/5 7/2/5 2/2/5
f 5/1/6 11/1/6 6/1/6
f 6/1/6 11/1/6 12/1/6

With the following texture applied as Albedo on a default Unity material (a bit odd since it was originally generated in MagicaVoxel)

I'm really at a loss for what could be causing these to show up. Only spotted them because I was testing an outline shader and it was outlining all the artifacts as the normals on those pixels were odd. With a pixel shader set to display _CameraNormalsTexture instead of the color the artifacts are still visible as variances in the normals as you can see in the image below.


texts: What's the best low cost ways to host your own "play in browser" games

texts: I've been developing games as a hobbiest/part-time indie for a few years now and have half a dozen games that I'm reasonably proud of. I was wondering if anyone could suggest good, relatively low cost options for setting up a web-site to host my games, playable natively in the browser, to more easily share them with friends, online communities, and potential employers.


texts: What is the simplest method to generate smooth terrain for a 2d game?

texts:
What is the simplest method to generate smooth terrain for a 2d game like "Moon Buggy" or "Route 960"?

I got an answer at stackoverflow.com about generate an array of random heights and blur them later. Yes, it's quite okay. But it would be better to give some points, and get a smooth curve.


texts: What is the purpose of the directory Packages in my Assets directory?

texts:
So far I used EditorWindow script but few minutes ago without and alert I have strange stuff in the Assets in the Editor.
I see now a new folder name Packages I can't figure out where it came from but for 100% I didn't import any packages at all.

Second when I put the mouse on it and right click I can't delete it:

This is how the Packages looks like, Very strange thing:

Another strange thing but maybe it's connected to this Packages is that in the Scene view window I have this blue thing like a line or something that if I click on it it will be blue if not clicking on it it's black. Not sure what it is. It's not an object in the Hierarchy. Not sure where it came from.

I tried to restart the Unity over again but nothing same strange stuff.

I'm using unity3d 2018.2.5f1 Personal. And windows 10 home 64bit version 1803.

I see the Packages folder on the Hard disk now but when I make double click to get inside I see only one small file: manifest.json

And I was working and working with json file format to save and load but I can't figure out what is going on in the scene view and in the assets.


texts: Godot 3.2 atlasTexture not creating any texture atlas

texts: When I try to use the new feature of godot that lets you import sprites as an atlasTexture, I dont' get any results.


texts: How to make a part of an object with navmesh agent rotate separately?

texts:
I have a game object (a Humvee jeep) and it has a turret gun on top of it.

What i want to do is while the vehicle is moving in a line the turret look at player. I tried rotating the turret gun with "Transform.rotation" and "transform.lookat()" but nothing happened.
Is it possible to move/rotate some part of an object with navmesh separately?


texts:
Suppose I have a bunch of 2D art in some vectorized format such as SVG. Is there an easy-ish way to render that directly without having to implement a full SVG renderer myself?

Of course I could rasterize it off-line (e.g. in the content pipeline) for different resolutions/zoom levels, but I would like to maintain the crisp visuals at continuous zoom levels that vector graphics offer.


texts: Canvas setTransform function clarification

texts:
I'm currently building some kind of fake-3D dungeon, and I'm facing some difficulties understanding the behavior of the setTransform() function.

Here's my simplified code:

var can = document.getElementById('c'),
    ctx = can.getContext('2d'),
    angle = Math.PI / 4;

ctx.fillStyle = "grey";

ctx.setTransform(1, Math.tan(angle), 0, 1, 0, 0);
ctx.fillRect(100, 0, 50, 50);

Here's also s JsBin with the same code for you to see the result: http://jsbin.com/oxaSIpe/7/edit

Changing the x coordinate in the fillRect seems to also affect the y coordinate.
It makes no sense. Skewing an element changes its position? No documentation mentions anything like that.

If anyone could please try to explain this function and its weird behavior, I would be very grateful.


texts: Why do I have to switch T(v) texture coordinates while importing OpenGL to Direct3D?

texts:
I am importing my code from OpenGL to Direct3D. My D3DTS_PROJECTION uses D3DXMatrixPerspectiveFovRH, and my D3DTS_VIEW uses D3DXMatrixLookAtRH to set a view equal to OpenGL's view. My question is why do I have to switch all of my 1.0000 Tex(v) texture coordinates to "minus value" in D3D to get equal texture mapping as in OpenGL.

OpenGL:

//T(u)   T(v)
1.0000,  1.0000,
0.0000,  1.0000,
1.0000,  0.0000,
1.0000,  0.0000,
0.0000,  1.0000,
0.0000,  0.0000,

0.0000,  1.0000,
0.0000,  0.0000,
1.0000,  1.0000,
1.0000,  1.0000,
0.0000,  0.0000,
1.0000,  0.0000,
// ...

Direct3D:

//           T(u)     T(v)
D3DXVECTOR2( 1.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f, -1.0000f)
D3DXVECTOR2( 1.0000f,  0.0000f)
D3DXVECTOR2( 1.0000f,  0.0000f)
D3DXVECTOR2( 0.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f,  0.0000f)

D3DXVECTOR2( 0.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f,  0.0000f)
D3DXVECTOR2( 1.0000f, -1.0000f)
D3DXVECTOR2( 1.0000f, -1.0000f)
D3DXVECTOR2( 0.0000f,  0.0000f)
D3DXVECTOR2( 1.0000f,  0.0000f)
// ...

Is it because Direct3D's origin (0.0) of texture coordinates lies in different place than in OpenGL?


texts: How to distinguish between different platforms using an interface

texts:
I'm creating a platform system using a raycast controller that uses an interface to perform different tasks based on the type of platform with which my player is currently colliding. Some of the platform types include ice, passable blocks and muddy ground.

I want to know how to better optimize my code, as I currently call Unity's somewhat expensive "GetComponent()" function every frame, even if I never change between blocks. What I'd like to do is only call GetComponent() when I change from one type of platform to a different type of platform (i.e. muddy ground --> ice), but don't know how to do this using an interface.

I thought I would be able to compare types using enums, but you're not allowed to declare types in an interface.

        if (hit)
        {
            //I'd only like to run this block of code if the type of platform changes
            var platform = hit.collider.gameObject.GetComponent<IPlatform>();

            State.IsCollidingWithPassablePlatform = platform.IsPassable;
            State.IsJumpBoosted = platform.IsJumpForce;
            State.IsBoosted = platform.IsForce;

            xForce = platform.XForce;
            yForce = platform.YForce;
            zForce = platform.ZForce;

            defaultParameters.accelerationTimeGrounded = platform.AccelerationTimeGrounded;
            defaultParameters.accelerationTimeAirborne = platform.AccelerationTimeAirborne;

Interface example:

interface IPlatform {

float AccelerationTimeGrounded { get; }
float AccelerationTimeAirborne { get; }

float XForce { get; }
float YForce { get; }
float ZForce { get; }

bool IsPassable { get; }

bool IsForce { get; }
bool IsJumpForce { get; }

Ice platform:

public class PlatformIce : MonoBehaviour, IPlatform {

public float AccelerationTimeGrounded { get { return accelerationTimeGrounded; } }
public float AccelerationTimeAirborne { get { return accelerationTimeAirborne; } }

public float XForce { get { return xForce; } }
public float YForce { get { return yForce; } }
public float ZForce { get { return zForce; } }

public virtual bool IsPassable { get { return false; } }

public bool IsForce { get { return false; } }
public bool IsJumpForce { get { return false; } }

[SerializeField]
private float accelerationTimeGrounded = 1.0f;
[SerializeField]
private float accelerationTimeAirborne = 3.0f;

private float xForce = 0;
private float yForce = 0;
private float zForce = 0;
}


texts: How do I respawn a prefab that matches the name of the game object I just destroyed?

texts:
In my game the player can interact with certain objects like coins, clouds and springs. After these interactions the game objects are destroyed. All of these game objects have their own properties, but their classes inherit from a master "WorldObjects" class that contains respawn information:

protected virtual void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Player"))
    {
        if (respawnObject)
        {
            Respawner.respawnPositions.Add(startPosition);
            Respawner.respawnTimes.Add(respawnTimer);
        }

        PlayerController = other.GetComponent<CharacterController2D>();
    }

    else return;
}

I have been able to respawn one type of object at a time by dragging a prefab to the first position in my objectsToRespawn array, but how do I send information to my Respawner class so that I can dynamically respawn the correct type of game object depending on the object I previously destroyed? Is it possible to compare my destroyed game object's name with its associated prefab, and then load the prefab into the array (or, if needed, a list)?

Here's my respawner class:

public class Respawner : MonoBehaviour
{
public GameObject[] objectsToRespawn;

public List<Vector3> respawnPositions = new List<Vector3>();
public List<float> respawnTimes = new List<float>();

private void Update ()
{
    if (respawnPositions.Count != 0)
    {
        RespawnObjects();
    }
}

private void RespawnObjects()
{
    for (int i = 0; i < respawnPositions.Count; i++)
    {
        respawnTimes[i] -= Time.deltaTime;

        if (respawnTimes[i] <= 0)
        {
            Instantiate(objectsToRespawn[i], respawnPositions[i], Quaternion.Euler(0, 0, 0));
            respawnPositions.RemoveAt(i);
            respawnTimes.RemoveAt(i);
        }
    }
}

Perhaps I should clarify, what I want to have happen is when I destroy a game object via OnTriggerEnter2D (like picking up a coin), that object sends its name or type or some sort of identification to the respawner class, which "queues" up the associated prefab, ultimately respawning it in its original location once the respawn timer for that object is 0.

This is my coin's OnTriggerEnter2D class (where the object is destroyed):

protected override void OnTriggerEnter2D(Collider2D other)
{
    base.OnTriggerEnter2D(other);

    Destroy(this.gameObject);
    Destroy(Instantiate(interactionEffect.gameObject, ObjectTransform.position, ObjectTransform.rotation) as GameObject,
        interactionEffect.main.duration * 2);
}


texts: How to convert Blender rotation angles to Unity rotation angles?

texts:
I add news cameras in my game. I have a problem with rotation, the result is not alway  the same as in Blender. I tried lot of ideas but today I do not have anymore.

Cameras 1, 2, 4 : good rotation

Cameras 3, 5 : bad rotation

Cam 1 (Blender):

Cam 1 (Unity): the fov is different

Cam 4 (Blender):

Cam 4 (Unity): the fov is different

Cam 3 (Blender):

Cam 3 (Unity): rotation is very different

Cam 5 (Blender):

Cam 5 (Unity): rotation is very different

This problem appears if camera orientation is "vertical"

Do you have a turn arround, a solution for me?

My code:

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

public class rotation_cams : MonoBehaviour
{
    private Vector3[] cams_loc;
    private Vector3[] cams_rot;
    void Start()
    {
        cams_loc = new Vector3[5];
        cams_rot = new Vector3[5];

        cams_loc[0] = new Vector3(79.7771f, 21.7574f, 109.795f);
        cams_rot[0] = new Vector3(95f, -45f, -200f);

        cams_loc[1] = new Vector3(78.0048f, 21.9854f, 110.314f);
        cams_rot[1] = new Vector3(87.0958f, 1.34464f, -160.515f);

        cams_loc[2] = new Vector3(78.3154f, 18.9402f, 111.654f);
        cams_rot[2] = new Vector3(169f, 59.3947f, -110.242f);

        cams_loc[3] = new Vector3(78.023f, 18.7094f, 111.375f);
        cams_rot[3] = new Vector3(89.4105f, 16.7202f, -128.303f);

        cams_loc[4] = new Vector3(79.5798f, 19.7249f, 111.743f);
        cams_rot[4] = new Vector3(55.0461f, 74.0926f, -220.475f);

        int i = 0;

        foreach (Vector3 vector_loc in cams_loc)
        {
            string camName = "cam" + i.ToString();
            GameObject currentCam = AddCamera(camName);

            currentCam.GetComponent<Transform>().position = new Vector3(cams_loc[i].x, cams_loc[i].z, cams_loc[i].y);

            Vector3 objRotation = new Vector3(cams_rot[i].x * -1, cams_rot[i].z * -1, cams_rot[i].y * -1);
            objRotation.x += 90f;

            currentCam.GetComponent<Transform>().eulerAngles = objRotation;

            i += 1;
        }
    }

    void Update()
    {

    }

    private GameObject AddCamera(string name)
    {
        GameObject gizmoPhoto = GameObject.Instantiate(GameObject.Find("cam"));
        gizmoPhoto.name = name;

        return gizmoPhoto;
    }
}


texts: How to fix artifacts when using equirectangular 360 panorama photo on sphere

texts:
I have a equirectangular 360 panorama photo. I tried to use it as a texture for a default Unity Sphere. The image had artifacts/visible seams, especially near the "poles" of the sphere (north pole and south pole).

Here is an example of the artifacts.

I also have the same image rendered by some third party apps, where it looks ok:

How can I fix this?


texts: I don't think my shaders are working, looking for help

texts:
Using sharpdx(directx 11) developing on UWP.
This is a link to a previous question of not being able to compile the shader files(written in hlsl) How to compile shader files in UWP Later I have found some method to avoid the original exception(unable to open or find shader files) but still the shaders seem not to be working.
My method to "avoid the original exception" is to change the file path to
System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "ProjectName")

If the method works, I would surely post it as an answer to the previous question
The current problem is no display on the screen(all black), while I can check the stored data in the vertex buffer using graphic diagnostics tools built in visual studio.

Here is my code for the shaders, problem may be going from here because this is the first shader file I've written. Please have a look and discuss may things go wrong.
pixel shader file Pixel_PS.fx
struct VertexOut
{
    float4 PosH : SV_POSITION;
    float4 Color : COLOR;
};

float4 PS(VertexOut pin) : SV_Target
{
    return pin.Color;
}

vertes shader file Transf_VS.fx
cbuffer dataBuffer : register(b0)
{
    matrix ViewProjection;
};

struct VertexIn
{
    float3 PosL : POSITION;
    float4 Color : COLOR;
};

struct VertexOut
{
    float4 PosH : SV_POSITION;
    float4 Color : COLOR;
};

VertexOut VS(VertexIn vin)
{
    VertexOut vout;
    // Transform to homogeneous clip space.
    vout.PosH = mul(float4(vin.PosL, 1.0f), ViewProjection);
    // Just pass vertex color into the pixel shader.
    vout.Color = vin.Color;
    return vout;
}

where I compiled them
byte[] vertexShaderByteCode = ShaderBytecode.CompileFromFile(this.path + "\\Transf_VS.fx", "VS", "vs_5_0");
                this.vertexShader = new D3D11.VertexShader(
                    device,
                    vertexShaderByteCode
                    );
                this.inputSignature = new ShaderSignature(vertexShaderByteCode);
                this.pixelShader = new D3D11.PixelShader(
                    device,
                    ShaderBytecode.CompileFromFile(this.path + "\\Pixel_PS.fx", "PS", "ps_5_0")
                    );

data structure definition
public struct ScatterVertex
    {
        SharpDX.Vector3 Position;
        SharpDX.Color4 Color;
    }

inputlayout initialization
this.inputLayout = new D3D11.InputLayout(
                    this.device,
                    inputSignature,
                    new SharpDX.Direct3D11.InputElement[]
                    {
                        new D3D11.InputElement(
                            "Position",
                            0,
                            SharpDX.DXGI.Format.R32G32B32_Float,
                            0
                            ),
                        new D3D11.InputElement(
                            "Color",
                            0,
                            SharpDX.DXGI.Format.R32G32B32A32_Float,//I'm not very sure whether or why I should use this option
                            0
                            )
                    }
                    );

Here's the projection matrix in the camera class, which is later sent to the constant buffer
private Matrix View { get { return Matrix.LookAtLH(this.Eye, this.Target, this.Up); } }
private Matrix Proj { get { return Matrix.PerspectiveFovLH(this.Fov, this.Aspect, this.Near, this.Far); } }
public Matrix WorldViewProject
        {
            get
            {
                Matrix wvp = (this.View * this.Proj);
                wvp.Transpose();
                return wvp;
            }
        }

If you need anything else to solve this, just let me know and I'll manage to get it.
Thank you!


texts: How can I edit the components of an instantiated prefab?

texts:
Is it possible to edit one or more components of an instantiated prefab ?

For example if you instantiated five cube prefabs. Is it possible to reference each of the cube prefab and change a value individually ? Such as changing its position or even its scale.

If possible how can it be done ? Another request is, if this can be done. Could it be in the Update() function so when the game is running values can be experimented with.


texts:
I need to limit the mipmap level loaded onto the device for certain textures, but I'm using a D3D9Ex-based engine, so I can only use D3DPOOL_DEFAULT, not D3DPOOL_MANAGED.

Microsoft's documentation says that I can use SetLOD

  for a managed texture.

Does that mean that I cannot use SetLOD in D3D9Ex?


texts: Pressed key doesn't run out of special powerups

texts:
So I'm making a game in Lua/Love2D and have a problem with my game logic. Mainly I have a spaceship that can use boost and stuff. That part is fine, I click space and it boosts up to speed quickly.

The problem is that if the person holds down space, they stay boosted, which is not the intended behavior. How do I make sure that once boost runs out, it decelerates to normal speed? This is how it is currently:

  Note: Normal speed, 1000. Max boost possible speed, 3000.

if love.keyboard.isDown('space') then
    if player.v < 3000 and UICounters.currentboost > 0 then
        player.v = player.v + 200
        if player.v > 3000 then
            player.v = 3000
        end
        UICounters.currentboost = UICounters.currentboost - 1
    end
else
    if player.v > 1000 then
        player.v = player.v - 100
    end
    if UICounters.currentboost < UICounters.maxboost then
        UICounters.currentboost = UICounters.currentboost + dt
    end
end


texts: Should references between assets be handled by name or ID or something else?

texts:
How should content or asset items be referenced in their serialized form?

For example, a material might need to reference several textures. The simplest way would be to use a path, relative to the base directory of the assets.

Alternatively, all content items could be referenced by an ID. I implemented it this way (using GUIDs), which allows content items to be renamed or moved without breaking references. However, this makes it more difficult to replace a content item (delete the original, then rename something else to the same name... requires copy/pasting GUIDs around). It also makes debugging missing content trickier.

Is there a clear winning option here?


texts: Create a "genie" effect in fragment shader GLSL

texts:
I have tried a while now to create a genie effect on a scrolling plane to emulate the background/floor from the Mad Hatter fight in Adventures of Batman and Robin (SEGA).
Judging the way the 16 bit era loved using scan-lines to create most of these (in this case amazing) effects I wanted to try and achieve this effect in GLSL. What I have tried to do so far was to adapt this tutorial code here and convert it to work in the fragment shader instead of the vertex shader, mostly because I haven't dabbled much with model loading (creating grids by hand isn't fun) but have created this monstrosity.

So far I am at step two where the float t gets introduced, instead of getting a leaning trapezoid like shape I only get this:
The square is just squished more on the x-axis instead of actually doing anything useful for me, this is my current fragment code for manipulating the image:

#version 330 core
precision lowp float;

out vec4 color;
in vec2 UV;

uniform sampler2D in_Tex_0;
uniform vec4 in_Val_0;

vec2 dist(vec2 coord)
{
    // xy range of transformation
    vec2 start = vec2( 0.0, 0.0 );
    vec2 end = vec2( 1.0, 1.0 );
    vec2 pos;
    // in_Val_0.x instead of size param in tutorial
    pos.y = mix( start.y, end.y, in_Val_0.x );
    float t = pos.y / end.y;
    pos.x = mix( start.y, end.x, t * in_Val_0.x );
    // should return a leaning trapezoid
    return coord * pos;
}

void main()
{
    // Pass through color data to bound framebuffer using distorted texture
    color = vec4( texture2D( in_Tex_0, dist( UV ) ) );
}

I'm suspecting there's something wrong with the ´t´ that gets added in the mix, but I am at a loss of what. Any idea of what might be wrong and/or how I could fix this?


texts:
Is it possible to cut a body from a texture in Farseer 3.0?

I have a texture converted to a body with multiple fixtures ( using BayazitDecomposer, CreatePolygon method, ..) and can even do it as a BreakableBody.

But when I try to cut it with the cutting tool, the fixture itself gets cutted but it's connections get discarded! So when I have 14 fixtures, and cut fixture 3 for example, fixture 3 gets cutted but 1,2 and 3-14 just go away.
Is there a way to do it? It would work already if I could convert the texture into a body with 1 fixture only, but I haven't figured out it that's possible. BayazitDecomposer creates the multiple verticles, but letting it away creates something weird and I get assert messages all the time.

I know I couldn't break it that way but I don't need that anyway when I could cut it.
The breaking is just the work around I'm using now.

Extending the cuttingtool to support multiple fixtures is very hard especially when you consider that in one cut multiple fixtures could be cutted and then connected again.


texts:
I have a list of points (3D) and want to draw a line connecting all points with a specified width. The line should be rendered in OpenGL (using OSG) as triangles.
The real challenge of this task is to make the line look "pleasant" for the user; meaning the joints should be round.

It should be similar to this:

Is there any library which brings this functionality?


texts: How can I divide a 3D mesh into small pieces?

texts:
I'm considering a manufacturing game. A player should assemble parts of an object in given time. The object will be a 3D mesh model. I want to automatically split the 3D mesh into many small pieces to be provided to players. Each divided piece is needed to have area as similar as possible. And I want to control the number of pieces too within range about 2~6. How can I do this?

I know the method to modify a given mesh like adjusting values of vertices, indices. All I need is the algorithm.


texts: Position and rotate a 2D point array into a 3D world

texts:
I have a set of 2D points (defining a flat 2D 'connect the dots' shape).
I want to calculate the 3D positions for these 2D points at a specific 3D position and rotation.

For example, say I have five 2D points forming the shape of a 2D hexagon. I want to place this hexagon shape at a specific location in my 3D world, at a specific rotation. I need to calculate new 3D coordinates for each of the 2D points.

If it matters, the 2D points will center around (0,0).

What magic formula do I need to do to accomplish this translation?
Is there a built in method (in Unity) to do this?

Each point will be perpendicular to the rotation angle/direction, so will I need to calculate the cross product?  Then somehow use this to remap each 2D point?

I should have paid more attention to this in school, all those years ago (I can't even remember if I actually learned this before!).

Any help will be appreciated. Thanks.

Here's some basic code to illustrate:

Vector3 position;     // Where in 3D to place the 2D shape
Quaternion rotation;  // What 3D rotation to apply to the 2D shape.  Should be a Vector3?
Vector2[] shapeIn;    // List of 2D points defining shape
Vector3[] shapeOut;   // List of updated 3D points at its new position and rotation

shapeOut = new Vector3[shapeIn.Length];

for (int p=0; p<shapeIn.Length; p++) {
    shapeOut[p] = MagicFormula(shapeIn[p]);
}


texts: Server-side physic simulations with hundreds of players

texts:
I’m currently working on a singleplayer physics-orientated game where I would like the physics to be simulated server-side. This because the game will have leadersboards, persistant player progression, etcetera and I want to prevent any type of cheating – basically a pure client-server architecture, the client is “dumb” and only displays what the server wants you to display.

The problem however is that the game will most likely be played by hundreds (maybe thousands) of people at the same time. This concerns me, as it will most likely kill server-processing power if I have to do and maintain hundreds of states at the same time.

I would have no problems moving all of the physics simulations to the client-side, but then I would really need a way to validate if the result of a client simulation is valid. However, I can't figure out how.

I have thought about running the simulation server-side once in a while to validate if the client is still playing fair, but I really want the server to have as less strain as possible.

Physics will become about as complex as the GDC 2011 demo by Glenn Fiedler, maybe even simpler. However, a lot more always-colliding rigid-bodies will be in a single scene and they will all be visible at once.

I have a hard time getting an answer to this particular case, as most resources on the web - again, Glenn Fiedlers site being a great one - speak about small-scale networked physics (eg. a FPS with 30 players, like Halo).

Any advice, websites, papers or the like on the subject will be very appreciated.

A recap of the questions I would like an answer to:

How feasible is a client-server model? Is my server-processing power concern legit and grounded?
Is it possible to reliably validate a physic simulation run by the client on the server? If so, how?


texts: Modeling speed of light information propagation in space combat sim

texts:
I'm working on a space combat sim that takes place over relatively vast areas (a cube of space ~20 light minutes to a side) and uses (mostly) realistic physics. One of the key elements I want to model is the propagation speed of information across the battle space -- that is, if Player A engages his main drive on one side of the battle space, there's a 20 minute delay before Player B sees it and can react to it

Even for relatively small battle spaces this is an important factor given the speeds involved. A 500m long ship doing 30kps is going to displace itself by its full length in 1/60th of a second, so even targeting an opponent just few tenths of a light second away are going to be affected by light lag.

I've not seen this done before, and I'm wondering if there are some best practices for modeling this. Right now I'm timestamping each event and marking it with a location, putting it into a queue, and then each tick checking to see if any of the objects in the game world are newly at the edge of the light cone and adding the event to their sensor queue. I will (but haven't yet) optimize it by removing any events that have already been sensed by all the objects that can possibly sense it, but still, I think this is going to get cumbersome pretty darn fast, and eat up a lot of cycles if there are hundreds of sensing objects in play (which is pretty routine).

Are there data models which would be better suited for this that I should check out?


texts: Why does my side-scroller character move in the wrong direction?

texts:
I'm trying to understand why my rectangle moves in the opposite direction I want it to.

I have a float for translation:

 glTranslatef(translate_x, 0, 0);

 if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
        translate_x += 5;
 }

This is the rectangle I'm drawing (I did use glpush and -pop):

glColor3f(250, 0, 0);
glBegin(GL_QUADS);
    glVertex2i(400, 400); // Upper-left
    glVertex2i(450, 400); // Upper-right
    glVertex2i(450, 450); // Bottom-right
    glVertex2i(400, 450); // Bottom-left
glEnd();

Whenever I press the spacebar, the rectangle moves to the opposite direction of where I want it to move. Why is this?


texts: Do I really have to write my own optimized model format?

texts: So I'm a brand new noob to the world of game dev and I'm starting off by trying to write my own game using C++ and openGL. I'm getting into loading models etc and while searching around for "the best format" I'm finding that most of the common formats are intended for porting between modelling applications and not necessarily for final representation of data when loading into a game environment. I'm being told through various sources that ultimately you want to use formats like collada etc and convert them into a custom binary format optimized for your game. Is this absolutely necessary? I understand the idea, that parsing a large XML or some other ASCII format is going to be slower than reading a binary file type but is it really going to be THAT big of a performance hit if I don't? I can't see it, but before I go and fill the assets directory of my game with dae or fbx files I thought I'd ask.


texts: Does it make the game more fun when the user is forced to progress through the levels sequentially rather than letting them pick and play?

texts:
For the first time in my game, I'm stuck with a real design dilemma.  I guess that's a good thing ;)  I'm building a word puzzle game that has five levels, each with 30 puzzles.  Currently, the user has to solve one puzzle at a time before moving to the next.  However, I'm finding the user occasionally gets stuck on a puzzle, at which point they can no longer play until they solve it.  This is obviously bad because many people will probably just quit playing the game and delete the app.

The only elegant solution I can find to helping the player get unstuck is changing the design of the game to allow the users to pick any puzzle to play at any time.  This way, if they get stuck, they can come back to it later and at least they have other puzzles to play in the meantime.  It's my opinion, however, that this new flow design doesn't make the game as fun as the original flow design where  the player has to complete a puzzle before moving to the next.  To me, it's like anything else, when you only have one of something, it's more enjoyable, but when you have 30 of something, it's far less enjoyable.  In fact, when I present the user with 30 puzzles to choose from, I'm concerned I might be making them feel like it's a lot of work they have to do and that's bad.  I even had a tester voluntarily tell me that being forced to complete a puzzle before moving to the next is actually motivating.

My questions are...

Do you agree/disagree?
Do you have any suggestions for how I can help the player get unstuck?

Thanks so much in advance for your thoughts!

EDIT: I should mention that I've already considered a few other solutions to helping the user get unstuck, but none of them seem like good ideas.  They are...

Add more hints: Currently, the user gets two hints per puzzle.  If I increase the hint count, it only makes the game more easy and still leaves the possibility of the user getting stuck.
Add a "Show Solution" button: This seems like a bad idea because it's my opinion this takes the fun out of the game for many people who would probably otherwise solve the puzzle if they didn't have the quick option to see the solution.


texts: Day and Night mode according to user's real local time

texts:
How do I make it so the texture of my plane is a black sky when it's night according to player's local time (say from 10 PM to 5 AM it's going to be black, and from 6 AM to 9 AM it's going to be a blue sky)?

Blue sky texture name is "bluesky"
Black sky texture name is "blacksky"

Thanks.


texts:
I'm having trouble coming up with a way to animate these 2D isometric sprites. The sprites are stored like this:

(Game Folder Root)/Assets/Sprites/(Sprite Name)/(Sprite Animation)/(Sprite Direction)/(Frame Number).png

So for example,

/Assets/Sprites/Worker/Stand/North-East/01.png

Sprite sheets aren't really viable for this type of animation. The example stand animation is 61 frames. 61 frames for all 8 directions alone is huge, but there's more then just a standing animation for each sprite. Creating an sf::Texture for every image and every frame seems like it will take up a lot of memory and be hard to keep track of that many images. Unloading the image and loading the next one every single frame seems like it will do a lot of unnecessary work. What's the best way to handle this?

The reason I am not using a sprite sheet is because these sprites are hi-res images with many animations which all have a large quantity of frames. The resulting sprite sheet would be massive. In case you're wondering, here was my implementation of creating animated sprites.

// Animation class declaration
class Animation
{
public:
        Animation(std::string path, int frames);
        ~Animation();
        void nextFrame();
        void gotoStart();
        bool loadFrames();
        sf::Texture& getActiveFrame();

private:
        int frameCount;
        std::string pathToAnimation;
        int currentFrame;
        sf::Texture frame[];
};

// Animation class implementation
Animation::Animation(std::string path, int frames)
{
        pathToAnimation = path;
        frameCount = frames;
}

Animation::~Animation()
{
        // destructor
}

void Animation::nextFrame()
{
        if(currentFrame < frameCount)
        {
            currentFrame = 1;
        }
        else
            currentFrame += 1;
}

void Animation::gotoStart()
{
        currentFrame = 1;
}

bool Animation::loadFrames()
{
        for(int i = 01; i < frameCount; i++)
        {
            if(!frame[i].loadFromFile(pathToAnimation + std::to_string(i) + ".jpg")) return false;
        }
        return true;
}

sf::Texture& Animation::getActiveFrame()
{
    return frame[currentFrame];
}

// Actor class declaration
class Actor
{
public:
        Actor();
        ~Actor();
        void setActiveAnimation(std::shared_ptr<Animation> anim);
        void draw(sf::RenderWindow& win);

private:
        sf::Sprite sprite;
        std::shared_ptr<Animation> activeAnimation;
};

// Actor class implementation
Actor::Actor()
{
    // constructor
}

Actor::~Actor()
{
    // destructor
}

void Actor::setActiveAnimation(std::shared_ptr<Animation> anim)
{
    activeAnimation = anim;
    activeAnimation->gotoStart();
}

void Actor::draw(sf::RenderWindow& win)
{
    sprite.setTexture(activeAnimation->getActiveFrame());
    win.draw(sprite);
    activeAnimation->nextFrame();
}

It's still not 100% where I'd like it to be but it's working and it's pretty easy to use.


texts: Publishing a game -- any way to target both WP7 and Win8 Store?

texts:
I'm at a dilemma which seems should soon become an important issue for a lot of developers.

If I build a game in XNA, I won't be able to publish it on the Windows 8 Store, as it would be a classic application -- and classic applications can't be sold on the store.

If I build a game in Metro DirectX, I would be able to sell it on the Store, but porting it to Windows Phone would involve porting it to Reach XNA, which in fact would likely involve more effort even than porting to OS X or Android -- both of which support C++. Of all the WinRT API that is supported on C++/JS/.NET, DirectX can only be programmed from C++. It's also unlikely that Microsoft will update Windows 7 or Vista to support the new DirectX features, although that would make the Metro DirectX the first new version of DirectX to stop supporting the immediate predecessor OS.

If I build a game in Pre-Win8 DirectX 9/10/11, I won't be able to sell it on the Windows Store or Windows Phone, but I could sell it on something like Steam. It would also involve the most amount of manual plumbing. In fact, DirectWrite, despite being part of DirectX 11, doesn't talk to Direct3D.

I'm getting really tired of all these restrictions -- artificial and otherwise -- and I'm coming to a point where I'm considering switching to a platform with a less fragmented API, like Android or Mac/iOS.

As far as bringing a game into market goes, excluding the actual market share of any platforms that I might consider, what other factors would help me in making a decision?

Just a few years ago this question was a lot easier to answer: if you were primarily concerned with Windows platforms, all you had to answer was whether you wanted DirectX, XNA, or something like SlimDX. If you made the wrong decision, no biggie -- all you really would have lost is XBox and the fairly small Windows Phone market.


texts: From camera coordinates to world coordinates

texts:
I want to calculate world coordinates from camera coordinates. However, I seem to have problems with my understandings of how matrices in HLSL work.

From world to camera is clear:

cameraPosition = mul(mul(worldPosition, view), projection);

Logic would now say that for the reverse, I could just use something like

worldPosition = mul(mul(cameraPosition, invProjection), invView);

However, when I check if it is correct with

cameraPosition = mul(mul(mul(mul(cameraPosition, invProjection),
                                   invView), view), projection);

I don't get the same point back anymore.

The inverses should be fine as view * invView produces the identity matrix etc.

What is my misunderstanding here? Even the simpler case does not work:

void VS_test(in  float4 inPosition            : POSITION,
             out float4 outPosition           : POSITION)
{
    outPosition = inPosition;
}

produces the triangle I want. However, using

void VS_test(in  float4 inPosition            : POSITION,
             out float4 outPosition           : POSITION)
{
    outPosition = mul(mul(inPosition, view), invView);
}

already produces no visible triangle. Same with

void VS_test(in  float4 inPosition            : POSITION,
             out float4 outPosition           : POSITION)
{
    outPosition = mul(inPosition, mul(view, invView));
}

Pixel shader is just a shader which returns a constant color.

UPDATE

I have 3D camera-space coordinates WITH z-buffer value, like (0, 0, zNear) for the point directly in the center of the screen. I want to know what world coordinates correspond to this by doing the whole view-transform backwards.


texts:
I'm working on a little game (which is also my first one) and I want to insert a splash screen at the beginning (after the Unity one).
I've finally achieved to add a fade-in and a fade-out transistion when the splash screen starts and ends, but the fade out is activated by a button and I wont to play it simply after a certain time.
I've made a script for that:

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

public class FadeInOut_2 : MonoBehaviour
{
    public Animation anim;

    IEnumerator Start()
    {
        yield return new WaitForSeconds(2f);

        anim.GetComponent<Animation>().Play();

        Application.LoadLevel(Application.loadedLevel + 1);
    }

}

The problem is: when I try to attach the animation the Inspector refuses to do it.

Any ideas?
Thanks


texts: timezone independant Date.now() for node.js game

texts:
I have a game I'm working on using node.js and socket.io. The issue I'm having, is I'm trying to have it so that players execute whatever actions they inputed about 50ms in the future, giving everyone a chance to stay relatively in sync.

I've got frame-independant code running, which works well until a client has a different time than the server.

to predict when the client should act out movement code from the server, I use

Date.now() >= command.timeStamp

The issue I'm having is that the client isn't in the same timezone as the server, for instance someone I'm testing with is just one minute above/below my server time, resulting in commands being 900 milliseconds in the past or future, which is non-ideal.

Is there some way I can use a common timestamp across clients and server?


texts: How can I get into opensource game development?

texts:
The short and sweet question

I'm new to game programming in general, so how do I go about making GOOD QUALITY opensource games?

What I have come across

There are a multitude of games that I have played on Linux that are just downright shameful. The graphics are terrible, the AI is lacking, and the replayability is little to none. Don't get me wrong; I have played some good opensource games such as World of Goo, Gish, and Aquaria; but I'm really missing out on good games over here in my Linux hut.

What I have found

So, I did a little research on how the games mentioned were made. Thus, I have started learning OpenGL and SDL using my C++ programming experience (which is about a year of programming, not much). I also picked up the following books, which were recommended from programmers on stack overflow:

Focus on SDL (The only let me post one link for now...)
The OpenGL Super bible
GEB and CODE

What I have been recommended

I have also talked to someone who is a fairly experienced programmer who recommends that I take the C++ route to gaming, and that OpenGL and SDL would be a good way to go. He also recommended that I start using versioning control with my programs (Git particularly). What are your opinions on that?

Hope that was clear, guys.
Let me know,
Immanu'el


texts: Create vertices + indices for cylinder with triangle strips

texts:
I'm trying to create vertex and index buffer for a cylinder (in OpenGL, but it shouldn't matter). I think my vertex buffer is fine (I checked drawing with GL_POINTS). Here's the code that builds it:

int sides = 10, slices = 40;
float radius = 3.5 * 10.0;

numVertices = sides * slices;
Vertices = malloc(sizeof(Vertex) * numVertices);

int angleincs = 2*M_PI/sides;
int cs_angleincs = 2*M_PI/slices;
float zval;
float zstep = height / (float)sides;

float i;

for(int m=0; m<slices; m++)
{
    int index = (m*sides);
    for (int n=0; n<sides; n++)
    {
        Vertices[index + n].Position.x = cosf(i);
        Vertices[index + n].Position.y = sinf(i);
        Vertices[index + n].Position.z = zval;

        i += angleincs;
    }

    zval += zstep;
}

I'm stuck at the index buffer generation. Any help on how to build it? I tried to adapt some code from a torus generator, and I get something that apparently resembles a cylinder but it's a bit weird and has a few extra weird triangles.

numIndices = (2 * (sides+1) * slices + slices);
Indices = malloc(sizeof(GLushort) * numIndices);

int n=0;
for (int i=0;i<slices; i++) {
    for (int j=0; j<sides; j++) {
        Indices[n++] = i * sides + j;
        Indices[n++] = ((i+1)%slices) * sides + j;
    }

    Indices[n++] = i * sides;
    Indices[n++] = ((i+1)%slices) * sides;
    Indices[n++] = ((i+1)%slices) * sides;
}

Thanks in advance.


texts:
I'm working in Unity, and I'm finding that the animator isn't working for what I'm trying to do, in my 2D game.  I want to build a specific animation, using sprite sheets, and be able to reuse the same animation with other sprites that are the same size and dimensions by cells. After some research, I find that it is impossible.

Instead, I'm trying to create my own animation script, but I don't understand how to tell Unity to draw only a section of the sprite. Something like in XNA, where you could render only a specific rectangle of a sprite using start and end coordinates.

How do I manually draw a part of a sprite sheet?


texts: What kind of digitizing tablet did developers use back in the day?

texts: I have had trouble getting the money together to buy a digitizing tablet, and it would cheer me up to know what kind of digitizing tablet the artists were using to create classic games like Super Mario World and Sonic The Hedgehog. Part of me feels that maybe there is a way to make games without 2000+ pressure sensitivity levels. Does anyone know which models were widely used by console developers at the height of 2d gaming, and what their specs were?


texts: Unity 2D: Inconsistent jump height in game window

texts:
Whenever I start the unity editor and play it in the Game windows, sometimes the object can jump higher sometimes it is just small jump. I didn't change any value in my script nor changed it in inspector window.

It usually happens when I restart the unity editor or having my computer shutdown / restart and reopening the project.

Here are the jump code

void jump() {
     if (isInGround) {
         float currentJumpForce = jumpForce * Mathf.Abs(rigidBody.velocity.x) / 3.53f;
         rigidBody.AddForce(Vector2.up * currentJumpForce);
         animator.SetTrigger("isJump");
     }
}

I place the code inside the FixedUpdate method, for what I have read the physics calculation should be inside FixedUpdate right?

private void FixedUpdate() {
    if (Input.GetKeyDown(KeyCode.UpArrow)) {
        jump();
    }
}

I have read many are having similar problem, but it really doesn't answer this question.

UPDATE:

I forget to explain it in the question. The jumpForce is calculated based on the velocity of the gameObject has. I capped the velocity to certain speed based on this code

void accelerate() {
     if (rigidBody.velocity.x <= maxSpeed) {
         rigidBody.AddForce(Vector2.right * acceletateForce);
     }
}

where maxSpeed is a constant. I know this is probably not the accurate way to cap the velocity, or is it? Maybe this is where it gets messed up?

I just kinda assume the velocity is the capped from the camera movement and the 'display' or the movement of the screen. It seems the same to me.


texts: Significant frame drop upgrading from Unity 2019 to Unity 2020

texts:
I used to use Unity 2019.4.22f1, but now that 2020.3.0f1 has been marked as LTS, I've decided to switch to it.
For no apparent reason, it seems like my game is getting consistently lower framerate, precisely, almost like it's cut in half. I used to get 800-1000 FPS in my game but now its around 400-500. I've tested with multiple things that are even more demanding, and where I used to get 500 fps, I now get 200 fps.
It's clear that this is likely a configuration thing, but I don't know which settings to change, if any of them have been.
There is this SX article here which didn't get answered and seems to have the same problem: Link
And this article which seems to talk about a similar problem, though it is marked as fixed: Link


texts: Optimizing black and white matrix block drawing

texts:
Disclaimer:
I am uncertain if this is the best place to post this question, so please advise me of how I can best find the answer if I am doing something wrong. I am asking this question because I am trying to optimize a drawing function of a PC game I am programming.

Preface: There is a matrix of blocks, that can be either on (black) or off (white). There will be different colors, but for the sake of simplicity I am presenting the problem to you as black and white only, so please imagine this matrix forming some random pattern like a QR code which would be a good example.

Problem: Instead of drawing each black block individually, I want to determine how to draw all black blocks using as minimum calls to my draw black rectangle function as possible.

Question: Is there any existing process that I can refer to so as to make my drawing process as efficient as possible, or how would I logically go about tackling this conundrum?

Edit: Tried to produce some example code for us to play with

std::vector<std::vector<bool>> matrix;

int width = 100;
int height = 100;

matrix.resize(height);

for(int h = 0; h < height; h++)
{
    matrix[h].resize(width);
    for(int w = 0; w < width; w++)
    {
        matrix[h][w] = random 1/0
    }
}

void draw()
{
    .. draw matrix using a minimum amount of calls to draw_rectangle
}

void draw_rectangle(int x, int y, int width, int height)
{
    .. draws a set of black blocks
}


texts:
Here is my problem: I am creating a game and I have a board made out of polygons (hexagons). I want to be able to click on the different tiles but I can't find a simple method. I understood how to detect a click on basic surfaces such as rectangle or pictures, but not with more complex shapes like hexagons. Is it possible to do so?
I first searched for a Pygame function close to this but I didn't find any. Then I searched for the sprites, and I think it is possible, but very long. And the last way I found was to simply detect the color. However I don't want to change the color of the tiles.
How can I detect a click on a polygon? (Hexagons specifically)


texts: Can't call GameCenter in my Unity game for iOS

texts:
I'm trying to integrate Game Center into my Unity 5 project and facings troubles. It seems that authentification is OK when the game starts on iOS device, a notification appears, but leaderboard button does not work, nothing happens when I tap GC button. I assigned the initiation of "ShowLeaderboard()" to GC button. Please, take a look at the script I use below. Hope to find a resolution for my issue. Thank you in advance.

using UnityEngine;
using UnityEngine.SocialPlatforms;
using UnityEngine.SocialPlatforms.GameCenter;
using System.Collections;

public class GameCenter : MonoBehaviour {

    public string leaderboardID = "mygameleaderboard";

    void Start () {
        AuthenticateToGameCenter();
    }

    private bool isAuthenticatedToGameCenter;
    public static void  AuthenticateToGameCenter() {
        #if UNITY_IPHONE
        Social.localUser.Authenticate(success => {
        if (success) {
            Debug.Log("Authentication successful");
        } else {
            Debug.Log("Authentication failed");
            }
        });
        #endif
    }

    public static void ReportScore(long score, string leaderboardID) {
        #if UNITY_IPHONE
        Debug.Log("Reporting score " + score + " on leaderboard " + leaderboardID);
        Social.ReportScore(score, leaderboardID, success => {
            if (success) {
            Debug.Log("Reported score successfully");
            } else {
                Debug.Log("Failed to report score");
                }
            });
        #endif
    }

    //call to show leaderboard
    public static void ShowLeaderboard() {
        #if UNITY_IPHONE
        Social.ShowLeaderboardUI();
        #endif
    }
}


texts: How do I protect my game with CD key / serial number?

texts:
So I've decided I want to keep pirated copies of my XNA game from accessing official game servers (which are moderated, so people who paid for the game will get the best experience) by disconnecting clients with wrong or generated, duplicate or banned CD keys (or serial numbers, since the game is digital and there are no CDs whatsoever).

How do I get that serial number protection system into my game (both clients and main authentication server), so it's not easily hackable?

Note that I have no experience with making good protection of that kind for software.

I've never done this before, but I understand the basics. I see why I can't do key checks on client, so it's fine by me to use login/pass authentication with one-time key entry.

Currently, the goal of this protection is to keep potential cheaters and disruptively behaving players out of official servers. Anyone can play on private servers with or without a key, but the chance they may get undesirable experience with other players is greater. I guess it's easy enough on purchasing players, since they have to be online to play on official servers.

Because hacking the client is too easy, I'm going to protect only the initial registration (and possibly server-side authentication) procedures, so nobody can steal the keys while they're being transfered.

See also:

How should multiplayer games handle authentication?


texts: Model gets distorted when rotating the camera

texts:
I'm currently developing my own 3d graphics engine and I'm having a hard time figuring out why my 3D models gets distorted when rotating the camera around.

This is my projection matrix. I'm following the OpenGL's Model.

def get_projection_mat(aspect_ratio, camera):
    fov = camera.fov
    z_near = camera.z_near
    z_far = camera.z_far
    top = math.tan(fov * 0.5) * z_near
    bottom = -top
    right = top * aspect_ratio
    left = -right
    projection_mat = np.identity(4, dtype=float)
    projection_mat[0, 0] = 2 * z_near / (right - left)
    projection_mat[0, 2] = (right + left) / (right - left)
    projection_mat[1, 1] = 2 * z_near / (top - bottom)
    projection_mat[1, 2] = (top + bottom) / (top - bottom)
    projection_mat[2, 2] = -(z_far + z_near) / (z_far - z_near)
    projection_mat[2, 3] = -2 * z_far * z_near / (z_far - z_near)
    projection_mat[3, 2] = -1
    projection_mat[3, 3] = 0

    return projection_mat

This is my view matrix:

def camera_matrix(self):
    camera_matrix = np.identity(4, dtype=float)
    camera_matrix[:3, 0] = self.left[:]
    camera_matrix[:3, 1] = self.up[:]
    camera_matrix[:3, 2] = self.forward[:]
    camera_matrix[:3, 3] = self.pos[:]

    return camera_matrix

This is how I get the ViewProjection matrix:

    projection_mat = get_projection_mat(self.aspect_ratio, self.camera)
    view_mat = self.camera.camera_matrix()
    view_mat = np.linalg.inv(view_mat)
    self.view_projection_mat = np.dot(projection_mat, view_mat)

And, finally, this is the ViewProjectionModel matrix:

    view_projection_model_mat = np.dot(model.transform_mat.T, self.view_projection_mat)

This is the method that I use to rotate the camera:

def rotate(self, yaw, pitch, degress=True):
    rotation_mat_y = helper.rotate_matrix_y(yaw, degrees)
    rotation_mat_x = helper.rotate_matrix_x(pitch, degrees)
    rotation_mat = np.dot(rotation_mat_y, rotation_mat_x)
    self.forward = np.dot(np.insert(self.forward, 3, 1), rotation_mat)
    self.forward = helper.normalized((self.forward / self.forward[3])[:3])
    self.up = np.dot(np.insert(self.up, 3, 1), rotation_mat)
    self.up = helper.normalized((self.up / self.up[3])[:3])
    self.left = np.dot(np.insert(self.left, 3, 1), rotation_mat)
    self.left = helper.normalized((self.left / self.left[3])[:3])

A video demo, showing the problem

To summarize, the order of multiplication is ProjectionMat X ViewMat x ModelMat x ModelFaces.
If it isn't clear by now, I'm using Python for this project.
Any help would be greatly appreciated.

With best regards,
João Pedro

EDIT: Like this?

    directions, r = np.linalg.qr(np.array([self.forward, self.up, self.left]))
    self.forward = directions[0]
    self.up = directions[1]
    self.left = directions[2]


texts: Unity with move gameobject line renderer

texts:
I create DrawLine class, I want my character to follow the line I draw.

How do I move my character on draw line renderer ?

Thanks!

public class DrawLine : MonoBehaviour
{

    public GameObject linePrefab;
    public GameObject currentLine;

    public LineRenderer lineRenderer;
    public EdgeCollider2D edgeCollider;
    public List<Vector2> fingerPositions;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            CreateLine();
        }
        if (Input.GetMouseButton(0))
        {
            Vector2 tempFingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            if (Vector2.Distance(tempFingerPos, fingerPositions[fingerPositions.Count - 1]) > .1f)
            {
               UpdateLine(tempFingerPos);
            }

        }
    }

    void CreateLine()
    {
        currentLine = Instantiate(linePrefab, Vector3.zero, Quaternion.identity);
        lineRenderer = currentLine.GetComponent<LineRenderer>();
        edgeCollider = currentLine.GetComponent<EdgeCollider2D>();
        fingerPositions.Clear();
        fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
        fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));

        lineRenderer.SetPosition(0, fingerPositions[0]);
        lineRenderer.SetPosition(1, fingerPositions[1]);

        edgeCollider.points = fingerPositions.ToArray();
    }

    void UpdateLine(Vector2 newFingerPos)
    {
        fingerPositions.Add(newFingerPos);
        lineRenderer.positionCount++;
        lineRenderer.SetPosition(lineRenderer.positionCount - 1, newFingerPos);
        edgeCollider.points = fingerPositions.ToArray();

    }

}

```


texts: How can I boost cache performance when storing objects in a scene with managed languages?

texts:
So, for reasons that I won't go into (has to do with my team more so than a good objective reason, unfortunately), I'm building a soft game engine in C# on top of SharpDX. C++ wasn't an option. I can't store objects contiguously in C# when it comes to reference types like classes, so I'm thinking about taking a data-oriented-design approach to storing objects in my scene. Thus, my scene looks a bit like this right now (all of the fields are structs because I can store them by value type, and thus contiguously):

public delegate void UpdateMethod (ref ModelData md, ref Transform t, ...)

class Scene
{
    ModelData[] models;
    Transform[] transforms;
    //...some other fields here
    UpdateMethod[] updateMethods; //delegate array

    void UpdateAll()
    {
         for (int i = 0; i < NUM_GAME_OBJECTS; i++)
        {
            if (updateMethods[i]!= null)
            {
                updateMethods[i](ref models[i], ref transforms[i], ...);
            }
        }
    }
}

The idea being that I can now store the objects contiguously as opposed to just an array of contiguous references to the data if I made each component a class.

Is this even a viable technique, or am I abusing the DOD paradigm? I'm storing all of my objects like this, not just my dynamic ones. Perhaps I could split it up into two sets of arrays for dynamic and non-dynamic, so I'm not tempting branch-predictor slow-downs on the if statement for UpdateAll()?

Will an approach like this create more issues than it attempts to solve? I will note that, while updating occurs here, I outsource the actual carrying out of the component functionality to other systems. For example, an input subsystem determines keys pressed, so an object could check in its unique update method denoted by the delegate; the update doesn't do everything, just behavior specific to that bundle of game object data.

This seems analogous to operating over columns in a row-major language, in that I'm killing performance gain of data locality; am I correct in concluding it would it be beneficial to wrap all of these fields into some GameObjectData wrapper struct, and just store those in an array?


texts: Why does my turn-based game loop allow the enemy to act repeatedly?

texts:
I'm trying to create a turn-based game in pyGame but hit a wall when trying to properly handle the main game loop. So I have something like this:

def loop(self):
    while self.stategame==1:
        for event in pygame.event.get():
            if event.type == QUIT \
            or (event.type == KEYDOWN and event.key ==    K_ESCAPE):
                self.stategame = 0

        if self.isPlayerTurn:
            self.events()
        else:
            self.enemyTurn()
        self.draw_map()

        pygame.display.flip()

The enemyTurn() function here is called multiple times after each player's move causing the enemies to move multiple tiles before the player does anything again. I'm a beginner in gamedev do I don't know how to overcome this and, in the first place, why does it hapen. Isn't the code supposed to be analyzed from top to bottom like in regular Python so that the enemyTurn() is called just once and then the game goes back to waiting for user input? How can I solve this problem and call the enemyTurn() just once each time the player makes a move?


texts: Cross-platform multiplayer game in JavaScript

texts:
I want to start creating a simple multiplayer, JavaScript based, cross-platform game. Think about it as a two player mario where players can shoot each other.

My question is what is the best way (or at least a feasible way) to implement multiplayer into the game. I was thinking about:

Running the game on the both clients, from which one of them is considered to be the server and the other is playing catch-up.
Using my web server only to establish the connection between the two clients (and forward requests between them, I think this is easier then trying to use some RTC peer-to-peer protocol).

I have never done any multiplayer game, so I do not know if this method is good. One flaw in the design is that the game becomes very hackable (as the one that is considered to be the server has control over all the legal move validations done).

So, my question is if, using this method, a playable multiplayer game can be implemented, where if one player clicks the "shoot" button pointing in a specific direction the other player would receive this data in a period of time short enough so that he can react to it. If not, what is another reliable way to create a JavaScript, cross-platform (web, mobile) game?

If I were to also run an instance of the game on the server for each duel betwen two clients I think the servers would be over-loaded very easily, so I don't consider this a solution.

PS: About the hackable part. Do you think it can be reduced if I can somehow implement checkings on both clients?

PS2: When I say multiplayer I mean over the internet, not a local ad-hoc multiplayer for mobile devices.


texts: What is the difference between sprites and tiles?

texts:
I'm making a game, where it came to adding a tile class, but i already have a sprite one, which does the same at first glance.
Can you explain the difference with a couple of examples?


texts:
I have the following code:

Vector3 nearSource = new Vector3(mState.X, mState.Y, 0.0f);
Vector3 farSource = new Vector3(mState.X, mState.Y, 3.0f);
Vector3 nearPoint = Main.main.GraphicsDevice.Viewport.Unproject(nearSource, Main.main.projection, Main.main.view, Matrix.Identity);
Vector3 farPoint = Main.main.GraphicsDevice.Viewport.Unproject(farSource, Main.main.projection, Main.main.view, Matrix.Identity);
Vector3 direction = farPoint - nearPoint;
direction.Normalize();

Ray ray = new Ray(nearPoint, direction);

When my camera is facing direction DOWN, it still says that farPoint.Y is greater than nearPoint.Y

Why would it be doing this? The farpoint should be futher down if that is the direction I am facing.


texts: anything wrong with a spherical camera view matrix?

texts: Is there anything inherently wrong, if you derive your view matrix from 2 spherical coordinates (say, phi and theta) on the unit sphere? The z-axis vector would be at, say (phi, theta), the y-axis at (phi, theta-90) and the x-axis vector at, say, (phi-90,theta). You would convert the points into  Cartesian coordinate system and put them into view matrix rows to obtain the view matrix. I never read about people using such a camera specification on SO or here, so is there something wrong with it?


texts: Problem with rendering multiple textures from same image (LWJGL 3)

texts:
I have started with LWJGL3 and trying to built game engine. I'm stuck on generating terrains.
I have one image that contains two textures.

So now for example I want to generate terrain with only texture 2, so my texture coordinates looks something like this :
textures :
(0.6f,0f)
(0.9f,1f)
.....

Everything is fine if terrain is not long, but if I stretch terrain on z-axis, terrain is using texture 1.
As you can see on image.
I just can't understand why is doing that ?


texts: DirectxMesh obj to cmo texture coordinates off

texts:
I'm having trouble getting the texture coordinates of the cmo to match how the mesh was unwrapped in blender. I am using the directxmesh to convert the obj to a cmo and the directxtk to load the cmo.

Relevant parts of code are as follows:

std::unique_ptr<DirectX::CommonStates> m_states;
std::unique_ptr<DirectX::IEffectFactory> m_fxFactory;
std::unique_ptr<DirectX::Model> m_model;

...

m_states.reset(new CommonStates(d3d11DeviceInterface.Get()));

m_fxFactory.reset(new EffectFactory(d3d11DeviceInterface.Get()));

m_model = Model::CreateFromCMO(d3d11DeviceInterface.Get(), L"unit.cmo", *m_fxFactory);

...

m_model->Draw(d3d11DeviceContextInterface.Get(), *m_states, local, view, proj);

The model and uv map in blender look like this:

Using the following directxmesh command:
meshconvert unit.obj -cmo -y -nodds

the model looks like this in the program:

I thought this would be a simple matter of flipping the texture coordinates by adding the -fliptc switch to directxmesh
meshconvert unit.obj -cmo -y -nodds -fliptc

But this changes the winding order resulting in backface culling on the wrong sides. Subsequently, I tried changing the culling face to clockwise with the -cw switch
meshconvert unit.obj -cmo -y -nodds -fliptc -cw

Now the backface culling was happening on the correct faces but the texture coordinates were still wrong.

I'm rather lost as to what I have done wrong.

Edit: I seem to have figured out what is going on. The image seems to be flipped around the V axis. If I manually flip the image the coordinates match up to what is shown in blender. It's a shame I can't seem to find an option in blender to flip the UV coords along the V axis.


texts: Getting help on collaboration with Unity especially programmers

texts: My team and I are currently creating a 3D tower defense game with Unity and are compromised of me a few animators modelers and programmers. However as I am still fairly new to Unity I have trouble figuring out ways to collaborate with them. I know not what practices or advice I could get on the front of developing this game. I was hoping someone here might have some insight as to how best to collaborate with all team members and what one might do to get a better flow of information and help or assistance when working on this project. We are all about an hour or more away from each other so we must work remotely to collaborate. Thank you in advance.


texts:
Recently I installed Ubuntu-Mate 16.10. Unity and Monodevelop works, but when I try to compile the javascript on Monodevelop, appears an error:

Error: Framework 'Mono / .NET 3.5' not installed. (Assembly-CSharp)

On 14.04 all works very well but not here....what is the way to fix this problem??

I searched on the internet and I can't find the answer.


texts: I am having a problem with my game showing on my Oculus. I checked mark "Virtual Reality Supported" in Player settings. When I run the exe, I right click to use the option to play on Rift, but it just plays on my Desktop(and it plays fine on its own). The Oculus Configurations Utility shows that my Oculus is "ready," but it doesn't detect to run on the Oculus. I haven't used my Oculus in awhile and use to having the direct to rift option and extended mode, so it's pretty foreign to me- so help is appreciated.


texts:
I'm pretty new to Unity and I just finished some courses and tutorial found in the official documentation. I'm now in the process to apply what I learned so far using different assets from the ones provided with the tutorial, to see if I understood all the material.
I'm trying to build a simple top-down game with some free asset I found online.
My tile palette is composed, among others, of tiles like these:

Now, in order to create something like this:
[sorry for the quality, I recreated it in gimp since I'm not on the computer where I have Unity now]

I had to create three Tilemaps under the same Grid. The botton tilemap contains the grass (sort order -2), the middle one contains the fence (sort order -1) and the top one contains the house (sort order 0).
My first question is: given the tileset I have, is this the most efficient way to obtain what I needed?
After having solved this problem I wanted to add a collider to the fence and to the house, but since they are on two different tilemaps I cannot use a composite collider to optimize the collider's layout. Is there another way to do this in a more efficient way?
Instead of using tiles for "interactable objects", should I use "proper" game objects instead?


texts: How can I export a 3D model with keyframes to use in Blender?

texts:
I'm currently trying to export some 3D data and load it into Blender, but I've encountered some problems at the time of processing the meshes. They all have keyframes (nothing too complex, just texture change and rotation) but I cannot use traditional Wavefront Obj to export it, because it does not support this data.

How can I export this keyframe information in a way Blender will understand?


texts: Why can't I change the size of my spheres in Unity?

texts:
I started to learn Unity. Now I make something like a solar system. I have one problem. What are the min and max sizes of the sphere? E.g. I have a radius of the Sun - 1.5 but it shows like the Sun has radius 1, I can't make bigger. But also I have the Earth with 0.01 size and the Moon with 0.009. But I can't make the Mercury with 0.03 radius.
So why when I'm creating a new sphere now I have only radius 1 and can't change it in Scene window?


texts: Trying to make a game with C++, using lists to store bullets and enemies, but they are not erased

texts:
I've been trying to make a pretty simple space shooter game with C++, and I have been having a lot of trouble trying to use lists to store enemies and bullets.

Basically I followed the post here almost exactly to store my bullets:

SDL Bullet Movement

I've done something similar to store my enemies.

However, when I call bullets.erase(it++), for some reason the bullet is not erased.

When the bullet movement is run for the next frame, it tries to re delete the bullet and segfaults the program.  When I comment out the erase line, it runs fine, but the bullets are then never erased from the list...

Is there any reason why the elements of the list aren't being deleted?  I also set it up to print the number of elements in the list for every iteration, and it does not go down after deleting.

Thanks!

EDIT:

Here's the specific code I'm using to store my enemies and having them act:

std::list<Grunt*> doGrunts(std::list<Grunt*> grunts)
{
  for(std::list<Grunt*>::iterator it = grunts.begin(); it != grunts.end();)
    {

      if((*it)->getHull() == 0)
        {
          delete * it;
          grunts.erase(it++);
        }
      else
        {

          (**it).doUnit(grunts, it);
          ++it;
        }
     }
  }

Grunt is my enemy class, and the list grunts is a global variable.  Is that my problem?  When I pass the global into the function it becomes local?  I assumed lists would be a reference type so thought this wouldn't be a problem.

Sorry if this was a dumb question, I'm very new to C++, this is the first major thing I'm working on.


texts:
I have a game that needs to use a rope-like mechanic should do two things.

Restrict Player's Movement within the length of the rope. In other words, some kind of rubber band that brings the player back to the rope imitating real world.
Rope sections should not go beyond their hinge limits

I'm using the Rigidbody2D.velocity to move the player, the hinges do not stop the player from moving beyond the rope's limits. Thus, causing this visually breaking of the joints.

This is more visible when we flip the player's scale x to -1 since we're moving the player to the left. This also causes the rope segments to spasm or rotate at absurd speeds.

The break force is set to Infinity. I tried looking online for a solution but I'm not entirely sure what joint to use.
These are my hinge settings:

Questions:

How do I fix the rope segments to not have these gaps?
How do I safely flip the player without causing problems in the rope?


texts:
Okay, so I am very new to Game Development and I imported a .png file(made in Paint) to the assets and that file contains just a circle and an oval, not touching and far apart from each other, both of them coloured blue. When I open the sprite editor and click on splice, then select Automatic and Delete existing options and then click slice, I do not get different sprites, one containing the circle and the other containing the oval. The image isn't sliced at all. I have also set the sprite mode to Multiple, but to no avail.

Can someone help me and tell me what I am doing wrong? The engine I am using is Unity.

This is the image.


texts:
I'm working on an animation system for an RTS game. Each unit has several animation states: Move, Idle, Engaging, etc.. Units also have a variety of "Animation Impulses" which are animations that get played on top of the animation state. They're for things like shooting or casting a spell. When the impulse finishes, the unit returns to its current animation state.

Using Unity Mecanim Animators, how can I make a system like this? Is there a way to PlayOneShot an impulse animation that reverts back to a base animation when the impulse finishes?

I.e. a unit is in the state of pointing his gun at the target. The unit fires its gun and acts out the recoil. After the recoil animation finishes, the unit returns to pointing its gun at the target.


texts: LibGDX - how to make sizeToAction relative to other corner than bottom-left?

texts:
I'm trying to resize a widget inside a Table.
It's a fullscreen widget and when Android Keyboard comes out, the widget is resized so it fits half of the screen from the top.

SizeByAction works from the left-bottom corner so it resizes the widget down, and I have to resize it up.

For now I use a hack with a parallel action and I change it's size and POSITION in the same time so it looks like a want (like it was staying in the left-top corner all the time).

I know there's a originX and originY but they're used to rotation, not resizing elements.

If someone did something like this before without a hack  like mine, I would be grateful for a tip! :)

How does the widget look like? It's a fullscreen widget:

How does it look after resize?

How I want it to look like?
I want it to rezise relative to it's left-up corner


texts:
If I have a model, such as a robot, I am able to swap its limb meshes out and replace them with other robot limb meshes by merely removing the limb mesh from the skeleton and attaching the new one to the appropriate bone.

Now I want to essentially do the same thing but with a skinned mesh, say a human/monster character. For example I want to swap a normal human arm for some bad-ass demon arm. How do I go about doing this as I believe I need to take into account skin/bone weights etc.

Didn't Spore do something similar? Although my skeleton would be predefined as opposed to the ones created in Spore.


texts: Create prefab asset from object without creating object in the scene

texts:
I am writing an editor tool that is supposed to generate prefab objects from a parsed TMX file.

Since this is a special case because I don't want to instantiate objects, but rather create them there are not much documentation on how to do this.

I have come up with a way that actually creates an .prefab file from a gameobject. But the problem is that when I do this, the gameobject itself is created and put into the hierarchy. I only want the .prefab asset file.

This is they way I am doing it now.

static void ConvertFile(string filepath) {
    // This function returns a "new GameObject()" with attached components
    // However, this function still puts the new game object in the scene & hierarchy
    // which is not what I want
    GameObject mapObject = mapLoader.fromFile (filepath);
    string filename = System.IO.Path.GetFileNameWithoutExtension (filepath);

    // Create prefab file from an object
    PrefabUtility.CreatePrefab ("Assets/" + filename + ".prefab", mapObject);
}

public GameObject fromFile(string filepath) {
    // Removed code that parses file for easy read
    GameObject gameObject = new GameObject ();
    return gameObject;
}


texts: Clockwise / counter-clockwise convention for Vector2.Rotate(float angle)

texts:
I am making a 2D game in Unity, and from what I understand, their convention is that an angle of 0 is up and increasing the angle rotates the object counter-clockwise.

  Sidenote: I made this assumption by looking at the rotation.z value in a transform's Inspector window. When it is 0, the object's transform.up points towards positive y. Increasing rotation.z rotates the object counter-clockwise, i.e. the object's transform.up points to negative X at an angle of 90 degrees. Let me know if this is wrong.

Considering the convention, where increasing the angle rotates counter-clockwise, what should my extension method Vector2.Rotate(this Vector2 vector, float angle) do?

My question is whether doing Vector2.up.Rotate(90) would result in a clockwise or counter-clockwise rotation, where clockwise would give Vector2.right and counter-clockwise would give Vector2.left.

At first it seemed initiative to me that it would obviously rotate clockwise. It's a positive number so therefore it rotates clockwise. I'm not sure where that bias comes from, but using Rotate(90) feels like it should rotate it to the right (clockwise).

After reasoning about it, I think it would make more sense to have Rotate(90) rotate counter-clockwise. Because the universe assumes higher/positive angle results in counter-clockwise rotation, the method must also respect that rule. But for some reason it doesn't seem intuitive to me that to rotate something clockwise, I would have to call Rotate with a negative number, Rotate(-90) // clockwise.

Is there an evidence-based way to make this decision?


texts:
I want that my sprite go always forward, and you can only control his direction moving right and left (on 360 degrees). I don't know why, but the movement it's senseless.

The constants to move and rotate:

const int POD_DEGRE_MOVE = 5;
const int POD_STEP_MOVE = 3;

The sprite initalization:

_dragonSprite->setPosition(Point(visibleSize.width / 2,_dragonSprite->getContentSize().height * 0.75));
addChild(_dragonSprite, 2);

The event key listener:

void GameScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event *event){
    _pressedKey = keyCode;

    switch (_pressedKey) {

    case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
        giro = -POD_DEGRE_MOVE;
        _isMoving = true;
        break;
    case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
        giro = POD_DEGRE_MOVE;
        _isMoving = true;
        break;

    }

}
    void GameScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event *event){
        if (_pressedKey == keyCode) {
            _pressedKey = EventKeyboard::KeyCode::KEY_NONE;
            _isMoving = false;
            giro = 0;
        }
    }

And the calculations of the new direction:

void GameScene::update(float dt) {

    _dragonSprite->setRotation(_dragonSprite->getRotation() + giro);
    _podVector = Vec2(cos(_dragonSprite->getRotation()) * POD_STEP_MOVE, sin(_dragonSprite->getRotation()) * POD_STEP_MOVE);
    Vec2 newPos = Vec2(_dragonSprite->getPosition().x + _podVector.x, _dragonSprite->getPosition().y + _podVector.y);

_dragonSprite->setPosition(newPos);
}

Another problem is that the sprite at the start moves to the right (because Cos(0)==1), so I rotate the image of the sprite 90 degrees to the right, to then rotate it again at the initialization 90 to the left so the sprite is in the right position and his start angle is 90 (sin(90)==1), but the angle is not 90, and it moves as he wishes.

The last problem I have with this is that when I press a key (right or left), the sprite stops, rotates, and starts again (a direction that is not the direction where the sprite is aiming, that's the main problem). The sprite shouldn't stop while you are moving it.

Can anyone help me?


texts: (Java + Slick) How to rotate the Graphics (g) around the X-Axis?

texts: I already tried it by using GL11.glRotatef(45, 1, 0, 0), but the result looks like this:


texts:
If embedding Pygame to C++ to have a game be an executable, is there any extra process I would have to use in order to use Pygame functions when embedding into C++? As opposed to just writing embedding code in C++ for normal Python code?

To clear cut the question I want to know if it's the same process without having to call different functions.

EDIT: My question is if I have to call different functions in C++ when embedding Python code that uses Pygame modules. I am NOT using pygame2exe nor py2exe. I never even mentioned those. My question is solely about code embedding.


texts: XNA 4.0 thick triangle strip to fix aliasing issues upon rotation

texts:
My triangle strip based lines are disappearing intermittently when I rotate my camera around the X axis.

I was advised that this is due to aliasing issues and that "At a certain angle when its edge is facing the camera your strip will disappear." So, I was told to give the strip some thickness.

Can someone tell me the best way to do this? Would it be to draw two strips directly on top of each other? This doesn't seem to solve the problem but perhaps I am doing it wrong.


texts: Vertex attributes with strides between them vs blocks of data

texts:
Using opengl, does it make a difference if I upload plain vertex attribute structs, and then define the strides between them using glVertexAttribPointer, or if I do something like this

//we have position, texCoords, and normal vertex attributes
//allocate enough room for all attributes, set it to null for now
glBufferData(GL_ARRAY_BUFFER, positions.size() + normals.size() + textCoords.size(), NULL, BUFFER_USAGE);

//set positions data
glBufferSubData(GL_ARRAY_BUFFER, 0, positions.size(), positions.data());

//... call glBufferSubData for normals and texCoords as well


texts:
Very simple and quick question which surprisingly I couldn't find an answer to over the internet: what is the equivalent of glUniformMatrixfv for opentk? I've browsed all the 7 overloads of GL.UniformMatrix4 and none of them seems correct to me and/or I have found any example usage for.

E.g. if I have a

Matrix4[] matrices;

variable (properly initialized etc..) that I want to map on a

mat4 matrices[2];

in glsl, which GL.UniformMatrix4 overload should I use?

P.S. Using OpenTK.Next NuGet package version 1.1.1616.8959


texts: Unity using different NaveMesh for the same position

texts:
I have differents environments (they are on the same position, and they are prefab) , each environment have differents obstacles.

The problem comes with the navMesh.

What I want is to have one navMesh for each environment and switch them at runtime

Example:

User choose Environment 1 ----> I switch to NavMesh 1
User choose Environment 2 ----> I switch to NavMesh 2

but every time I bake the navmesh it override the last one,
also, How I can switch between navmesh?

Thanks in advance


texts: How can I get the "SelfActor" in OnBeginActorOverlap?

texts:
The signature it takes is

void ( AActor* OtherActor )

However, The actor that is handling this event is not involved in the overlap. How can I access the actor that owns this delegate? Assuming I can't store a reference to this elsewhere. Is there another delegate that takes that parameter? Is this reference stored in OtherActor somewhere?


texts: Perlin noise looks uncoherent on higher z

texts:
I was experiencing with my Perlin noise function and I tried to animate a 2D noise by changing the z value of a small amount every frame. However, as z increases, the result becomes stranger and stranger, looking like this:

Why is this happening? How could I solve this?

Here's the Lua code that could be wrong (as asked):

function perlin.fade(t)
    return t * t * t * (t * (6 * t - 15) + 10)
end
function perlin.lerp(t, a, b)
    return a + t * (b - a)
end
function perlin.grad(hash, x, y, z)
    local h = hash % 16
    local u
    local v
    if (h < 8) then u = x else u = y end
    if (h < 4) then v = y elseif (h == 12 or h == 14) then v = x else v = z end
    local r
    if ((h % 2) == 0) then r = u else r = -u             end
    if ((h % 4) == 0) then r = r + v else r = r -v end
    return r
end
function perlin:noise(x, y, z)
    y, z = y or 0, z or 0
    local X = math.floor(x) % 256
    local Y = math.floor(y) % 256
    local Z = math.floor(z) % 256
    x = x - math.floor(x)
    y = y - math.floor(y)
    z = z - math.floor(z)
    local u = perlin.fade(x)
    local v = perlin.fade(y)
    local w = perlin.fade(z)
    local A  = self[X + 1] + Y
    local AA = self[A + 1] + Z
    local AB = self[A + 2] + Z
    local B  = self[X + 2] + Y
    local BA = self[B + 1] + Z
    local BB = self[B + 2] + Z
    return perlin.lerp(w, perlin.lerp(v, perlin.lerp(u, perlin.grad(self[AA + 1], x    , y    , z    ),
                               perlin.grad(self[BA + 1], x - 1, y    , z    )),
                       perlin.lerp(u, perlin.grad(self[AB + 1], x    , y - 1, z    ),
                               perlin.grad(self[BB + 1], x - 1, y - 1, z    ))),
               perlin.lerp(v, perlin.lerp(u, perlin.grad(self[AB + 2], x    , y    , z - 1),
                               perlin.grad(self[BA + 2], x - 1, y    , z - 1)),
                       perlin.lerp(u, perlin.grad(self[AB + 2], x    , y - 1, z - 1),
                               perlin.grad(self[BB + 2], x - 1, y - 1, z - 1))))
end


texts: XNA Rendering vertices that only appear within the cameras view

texts:
I'm making a game in XNA and I recall hearing that professionally made games use a technique to only render the polygons that appear within the cameras projection. I've been trying to find something on this to do something similar in my game, could anyone point me in the right direction? Right now all I have is a plane/grid of vertices that you can set the X/Y on which is drawn using DrawUserIndexedPrimitives, but I plan to make a bunch of props as scenery items and I can imagine myself running into issues later on if I don't address this now.

Thanks


texts:
OK guys i have tried lots of things and researched but cannot find a solution please someone give me hope.. So on my phone when i am playing i want to shoot with a screen button in the canvas that is the entire screen size, and when i click it i can shoot towards where my finger is clicked "This works"... now my problem is whilst i am shooting when i also use my up and down button to move my player at the same time my gun stops moving towards my finger and instead moves towards my up and down buttons.. What can i do to fix this?

public void ShootButton()
    {

    timer = 0;
    Face = true;
    //if finger is press on Shootbutton
    //then activate this
    Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; // subtracting the position of the player from the mouse position.
    difference.Normalize(); //normalizing the vector meaning all the sum of the vector will be = to 1.

    float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;//find the angle in degree.
    WeaponTrans.transform.rotation = Quaternion.Euler(0f, 0f, rotZ + rotationOffset);
    if (reloading == false)
    {
        if (fireRate == 0)
        {
            {
                Shoot();
            }
        }
        else
        {
            if (Time.time > timeToFire)
            {
                timeToFire = Time.time + 1 / fireRate;
                Shoot();
            }
        }
    }
}


texts: Why distant objects are being drawn in front of close objects?

texts:
I am rendering two cubes in the space using XNA 4.0 and the layering of objects only works from certain angles.

Here is what I see from the front angle (everything ok)

Here is what I see from behind

This is my draw method. Cubes are drawn by serverManager and serverManager1

        protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        switch (_gameStateFSM.State)
        {
            case GameFSMState.GameStateFSM.INTROSCREEN:
                spriteBatch.Begin();
                introscreen.Draw(spriteBatch);
                spriteBatch.End();
                break;
            case GameFSMState.GameStateFSM.GAME:
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

                // Text
                screenMessagesManager.Draw(spriteBatch, firstPersonCamera.cameraPosition, fpsHelper.framesPerSecond);

                // Camera
                firstPersonCamera.Draw();

                // Servers
                serverManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix);
                serverManager1.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix);

                // Room
                //roomManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix);

                spriteBatch.End();

                break;
            case GameFSMState.GameStateFSM.EXITGAME:
                break;
            default:
                break;
        }

        base.Draw(gameTime);
        fpsHelper.IncrementFrameCounter();
    }

serverManager and serverManager1 are instances of the same class ServerManager that draws a cube. The draw method for ServerManager is:

        public void Draw(GraphicsDevice graphicsDevice, Matrix viewMatrix, Matrix projectionMatrix)
    {
        cubeEffect.World = Matrix.CreateTranslation(modelPosition); // Set the World matrix which defines the position of the cube
        cubeEffect.View = viewMatrix; // Set the View matrix which defines the camera and what it's looking at
        cubeEffect.Projection = projectionMatrix;

        // Enable textures on the Cube Effect. this is necessary to texture the model
        cubeEffect.TextureEnabled = true;
        cubeEffect.Texture = cubeTexture;
        // Enable some pretty lights
        cubeEffect.EnableDefaultLighting();
        // apply the effect and render the cube
        foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            cubeToDraw.RenderToDevice(graphicsDevice);
        }

    }

Obviously there is something I am doing wrong. Any hint of where to look? (Maybe z-buffer or occlusion tests?)


texts: Why is Reinforcement Learning so rarely used in pathfinding?

texts:
The venerable shortest-path graph theoretic algorithm A* and subsequent improvements (e.g., Hierarchical Annotated A*) is clearly the technique of choice for pathfinding in game development.

Instead, it just seems to me that RL is a more natural paradigm to move a character around a game space.

And yet I'm not aware of a single game developer who has implemented a Reinforcement Learning-based pathfinding engine. (I don't infer from this that the application of RL in pathfinding is 0, just that it's very small relative to A* and friends.)

Whatever the reason, it's not because these developers are unaware of RL, as evidenced by the fact that RL is frequently used elsewhere in the game engine.

This question is not a pretext for offering an opinion on RL in pathfinding; in fact, i am assuming that the tacit preference for A* et al. over RL is correct--but that preference is not obviously to me and i'm very curious about the reason for it, particularly from anyone who has tried to use RL for pathfinding.


texts: Unity/UNet without a lobby: How do you get an ordered list of participants (network players)?

texts:
Please imagine a turn based multiplayer game. Right now there's no lobby in place and connections are established using Unity's Network Manager HUD.

Now on the server, how can you get a list of all the match participants? Preferably ordered - something like the player on the host should be player 1, the first player who joined the match should be player two, the second player who joined should be player three....

Any advise is welcome,
thank you.