texts: How would I get this to UV map correctly?

texts:
Alright so I have my code to draw out a big landscape using C++ and DirectX. I had it textured with one texture and then needed to add more. I saw people doing it where they had 1 texture image and the image contained 2 textures. Thats what I made, it's a 256x128 image. My problem now is that since my terrain automatically generated the coordinates to UV map 1 texture now it is displaying both textures. I need to make it so when the height of the world is high enough it is 1 texture and everything under is another texture. My code for the UV coordinates,

Vertices[y * WIDTH * x].U = x / 1.28;

Vertices[y * WIDTH * x].V = y / 1.28;

those are my mapping coordinates, X is the current X value of the vertice it is drawing and the Y value is its current y position. The heightmap is 128x128 so I divided by 1.28 to make it so that each polygon had the texture UV mapped on it. The height is calculated as well since I am loading a heightmap and im trying to get it so when it is high enough it UV maps 1 half of the image and if it is the other it UV maps the other side of the image. Someone please help!


texts:
I have a list of game objects I'm trying to check collision against. My collision system is using code ive seen posted here before, but I'm not sure where I'm going wrong here.

 private bool Intersects(Rectangle player, Rectangle other, CollisionDirection direction, out Vector2 depth)
    {
        if (direction == CollisionDirection.Vertical)
        {
            depth = new Vector2(0, GetVerticalIntersectionDepth(player, other));
        }
        else
            depth = new Vector2(GetHorizontalIntersectionDepth(player, other));

        return depth.Y != 0 || depth.X != 0;
    }

    public float GetHorizontalIntersectionDepth(Rectangle rectA, Rectangle rectB)
    {
        float halfWidthA = rectA.Width / 2;
        float halfWidthB = rectB.Width / 2;

        float centerA = rectA.Left + halfWidthA;
        float centerB = rectB.Left + halfWidthB;

        float distanceX = centerA - centerB;
        float minDistanceX = halfWidthA + halfWidthB;

        if (Math.Abs(distanceX) >= minDistanceX)
            return 0;

        return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
    }

    public float GetVerticalIntersectionDepth(Rectangle rectA, Rectangle rectB)
    {
        float halfWidthA = rectA.Height / 2;
        float halfWidthB = rectB.Height / 2;

        float centerA = rectA.Top + halfWidthA;
        float centerB = rectB.Top + halfWidthB;

        float distanceX = centerA - centerB;
        float minDistanceX = halfWidthA + halfWidthB;

        if (Math.Abs(distanceX) >= minDistanceX)
            return 0;

        return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
    }

    private void CheckCollisions(CollisionDirection direction, List<GameObject> objects)
    {
        foreach(GameObject obj in objects)
        {
            Vector2 depth;
            if(Intersects(CollisionRectangle, obj.g_CollisionRectangle, direction, out depth))
            {
                g_WorldPosition += depth;
                Debug.WriteLine("true");
                if (direction == CollisionDirection.Horizontal)
                    g_Velocity.Y = 0;
                else
                    g_Velocity.X = 0;
            }
        }
    }

And in my update method I do this.

....
if(ks.IsKeyDown(Keys.S))
        {
            g_WorldPosition.Y += 10f;
            playerFacing = Direction.DOWN;
            CheckCollisions(CollisionDirection.Vertical, objectList);
        }
        if(ks.IsKeyDown(Keys.A))
        {
            g_WorldPosition.X -= 10f;
            playerFacing = Direction.LEFT;
            CheckCollisions(CollisionDirection.Horizontal, objectList);
        }
...

In the CheckCollision method the Debug line is writing true to the output even when i'm not colliding with anything. I know the g_CollisionRectangle is being set correctly because I have lines being drawn around the outside of each collidable object.

What happens is my player kinda moves sporadically because I'm getting collisions in places where I shouldnt.
Can anyone see where I'm going wrong here? I realize that g_Velocity is not being used in my update method, but I don't think that it should effect what is happening at this point. From what I can tell, my GetVertical and GetHorizontal methods are wrong somewhere because of the Debug line in the CheckCollision method.


texts: Quaternion rotation is inverse of what I expect

texts:
I'm trying to learn quaternions and decided to implement my own quaternion class.

To test it I made a couple vertex shaders, one that gets a model matrix (calculated from the quaternion) and another that gets the rotation quaternion directly and rotates vertices in-shader.

I then feed these a quaternion that rotates around the Y axis t / 10000 radians (t = time):

const rotation = Quat.fromAxisAngle(new Vec3([0, 1, 0]), t / 10000)

The result surprises me because my model is rotating counter-clockwise but I expected it to rotate clockwise, since the angle is increasing (checked it, quat's xyz increase with time). Rotation around the X or Z axes is also backwards.

All translations as well as matrix rotations work as expected in my coordinate system. I suspect my formulas are wrong, and probably assume +Z is forward. If I transpose my model matrix (or post-multiply with it) it rotates as expected, which suggests it's a handedness problem.

Where are my formulas wrong and how can I understand the math behind this?

Details

My matrices are column-major in memory (to match GLSL's mat4).
My coordinate system is +X right, +Y up, -Z forward.

My code

Quaternion from axis + angle

function fromAxisAngle(axis: Vec3, angle: number, dest = new Quat()): Quat {
  angle *= 0.5
  const sin = Math.sin(angle)

  dest.x = axis.x * sin
  dest.y = axis.y * sin
  dest.z = axis.z * sin
  dest.w = Math.cos(angle)

  return dest
}

Note: I noticed if I negate this quaternion's x, y and z, everthing works as expected. Is this the root cause? I thought quaternions didn't have handedness!

Since this is actually just inverting the quaternion (and thus its rotation) I'm afraid I'm just patching over the root cause. I don't want to patch the issue, I want to fix my math!

Matrix from quaternion

toMat4(dest = new Mat4()): Mat4 {
  const { x, y, z, w } = this

  const x2 = x + x
  const y2 = y + y
  const z2 = z + z

  const xx = x * x2
  const xy = x * y2
  const xz = x * z2
  const yy = y * y2
  const yz = y * z2
  const zz = z * z2
  const wx = w * x2
  const wy = w * y2
  const wz = w * z2

  // Notice matrix is column-major
  // Source:
  // https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix
  dest.init([
    1 - (yy + zz), xy - wz,       xz + wy,       0,
    xy + wz,       1 - (xx + zz), yz - wx,       0,
    xz - wy,       yz + wx,       1 - (xx + yy), 0,
    0,             0,             0,             1,
  ])

  return dest
}

Matrix vertex shader

precision mediump float;

attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;

uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;

varying vec2 vUV;

void main(void) {
  vUV = aVertexUV;

  gl_Position = uProjectionMatrix * uViewMatrix * uModelMatrix * vec4(aVertexPosition.xyz, 1.0);
}

Quaternion vertex shader

precision mediump float;

attribute vec3 aVertexPosition;
attribute vec2 aVertexUV;

struct Transform {
  float scale;
  vec3 translation;
  vec4 rotation;
};

uniform Transform uModel;
uniform Transform uView;
uniform mat4 uProjection;

varying vec2 vUV;

// Source:
// https://twistedpairdevelopment.wordpress.com/2013/02/11/rotating-a-vector-by-a-quaternion-in-glsl/
vec3 rotateVector(vec4 quat, vec3 vec) {
  return vec + 2.0 * cross(cross(vec, quat.xyz) + quat.w * vec, quat.xyz);
}

void main(void) {
  vUV = aVertexUV;

  vec3 world = rotateVector(uModel.rotation, aVertexPosition * uModel.scale) + uModel.translation;
  vec3 view = rotateVector(uView.rotation, world * uView.scale) + uView.translation;

  gl_Position = uProjection * vec4(view, 1.0);
}


texts: How to create tilted (height) isometric tiles

texts:
This is perhaps best explained pictorially. I am trying to create a 2.5D isometric game. My vision is for the game to look something like my goal:

I am not a graphics artist, so I'm having some trouble creating the "tilted" tiles to simulate terrain of different height. Creating the basic isometric tile was easy using the following steps:

Create a 64x64 square version of the tile
Rotate by 45 degrees
Scale the height down by a factor of 2

Creating the "tilted" tiles is more of a challenge. At my disposal I have Photoshop, but I am far from an expert at using it. Here is my current problem:

I am not sure how I can manipulate vertices, otherwise this would be easy, but basically, to get a "tilted" tile from my basic isometric tile, all I need to do is to shift the bottom and the right vertex down by 16 pixels, while fixing the other two vertices. This would generate the tile I want.

What is an easy way to accomplish this. Is Photoshop the right tool for this? Any suggestions?


texts:
I was recently introduced to a way of picking in OpenGL known as pixel picking (or color picking).

From my understanding, how this is done is that the scene is rendered to the back buffer with a different rgb color representing each object. By reading the color of the pixel clicked by the cursor, the relevant object can be picked. The immediate issue I can think of when using this method is that during the picking process, the scene have to be rendered 2 times, once for picking and another time for display. Additonally this also limits the it to 256^3 unique objects for picking.

With this, I would assume this is a much more accurate way of "raycast" than to use physics raycast. By placing a camera at the raycast source, render once for "raycast" picking, and resetting the camera to the original position for normal render. This would reduce issues of "bullet hitting invisible walls" as its not dependent on physics collision, which can be affected by convex hulls for complex meshes.

Is there any reason why this method is not used? Could it be over complication? Or perhaps it is what is happening behind the scenes in raycasting?

As an example where pixel picking might be better would be when raycasting through a wire fence. Most wire fence models are just textures with a transparent channel, giving the illusion of a wire fence while saving on geometry by having 1 single plane. Using color picking, what the player see is what the camera picks. Whereas in raycast, the raycast will not shoot through the plane unless it doesnt collide with the plane at all.


texts: How do I disable texture filtering for sprite scaling in XNA 4.0?

texts: I have a sprite that I'm trying to scale up in XNA, but XNA is applying some sort of texture filtering that smooths it and makes it look ugly. I'd like it to just do pixel doubling instead of interpolation. How would I accomplish that?


texts: Destructible objects for multi-player game in Unity

texts:
I am working on 3D multi-player shooter game
in Unity using SmartFoxServer

Since I need to implement some destructible objects in the game
I tried to use these assets:

Fracture
https://www.assetstore.unity3d.com/en/#!/content/7193

CaronteFX
https://www.assetstore.unity3d.com/en/#!/content/56698

things are working well for single player but
I am not sure how to tell the server to do same destructions for other players


texts: Is the way I remove objects causing a memory leak?

texts:
The game I'm working on consumes memory, and the memory used in megabytes increases around 2MB every 4 seconds.

It starts at 5MB and grows to hundreds of megabytes in minutes.

I was careful, and have little to no new variable declarations in the main game loop (and the existing ones are integers and floats, not SDL_Surface's and images).

However, I keep creating new instances of classes, such as bullets and enemies, but I'm also careful with those:

/* Is a bullet out of the screen? Remove it from the list! */
for (i = 0; i < bullets.size(); i++) {
  if (!bullets[i].is_on_screen(screen))
    bullets.erase(bullets.begin() + i);
}

I remove them from the respective vectors when they are no longer needed, and with enemies too:

/* Is the enemy death? Put it out of the array! */
for (i = 0; i < enemies.size(); i++) {
  if (enemies[i].health <= 0) enemies.erase(enemies.begin() + i);
}

Also, I create new Enemy(ies) with an image, but I only load the image on the beginning of the game, and then pass a pointer of it to the newly created class, so that it can draw it. I'm not creating hundreds of new images of enemies and bullets, am I?

When I erase the instances from the vectors, am I not fully deleting them from RAM?


texts: How to stop and start sprite sheet flipbook materials in a widget blueprint?

texts: I have a flipbook material I created from a sprite sheet to add some fireworks to a game I'm working on. I have the material set up and it is showing the animation of the firework like it should. However the animation in the material always repeats forever in a loop. I added an image to a widget to display the flipbook animation in a widget blueprint. The animation is shown in the blueprint as expected. The problem I have is getting the animation to start only when I show the animation. Being that the animation in the flipbook material is always looping, every time I show the image to show the firework, it seems to always start in a random frame, rarely is that frame actually the first frame. I read that I can control the speed of the animation in the flipbook. How can I stop the flipbook animation from looping indefinitely and only start the animation once I show the widget containing the image used to show the flipbook animation?


texts:
I'd like to build and package all the ports of my Unity game through a scripting system. Linux and Windows work fine through the Unity command line options, but there is none for WebGL.

For WebGL, the only existing solution seems to be its BuildPipeline. There is a gist with some sample code that has been referenced quit a few times. I changed its content to look like this:

BuildPipeline.BuildPlayer(scenes, "./WebGL-Test", BuildTarget.WebGL, BuildOptions.None);

and call it with unity-editor-beta -executeMethod WebGLBuilder.build  (Btw, is there a way to call this method from within Unity? It doesn't help I have to restart Unity each time I want to test if the script works). It will fail with the following error:

Assets/Scripts/WebGLBuilder.cs(18,3): error CS0103: The name `BuildPipeline' does not exist in the current context
Error building Player because scripts had compiler errors

I also tried to use the BuildPlayerOptions class instead but no success. How do I get WebGL to build automatically?


texts:
need some help with HLSL. Each charater in my game shows a fire range arc (which is a textured model) which show how far the guy can shoot, see

It looks ok, but I hate the fact that it shows even behing buildings. Now I already have a shader for rendering the Arc (where I only manipulate the u coordinate to achive oscilating effect) and I'm pretty sure that I can use the Shadow map approach for that - generate Shadow map as seen by the camera (my deferred renderer takes care of that), then when rendering the arc, compare current Depth to the one stored in shadow map and voila..

But I just can't get it to work. I know the theory, but I'm no expert in HLSL and shadow mapping...

Here is the code I have

...
float4x4 World;
float4x4 View;
float4x4 Projection;

float4x4 ObserverWVP; // of the character casting the arc

texture DepthMap; // as seen by the camera
...
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinates : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TextureCoordinates : TEXCOORD0;
    float4 Observer : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    output.Observer = mul(input.Position, ObserverWVP);

    output.TextureCoordinates = input.TextureCoordinates;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    ...

    float2 temp = (input.Observer.xy / input.Observer.w) * 0.5 + 1; // half pixel
    float depth2 = tex2D(DepthSampler, temp);
    float depth = input.Observer.z / input.Observer.w;

    if (depth < depth2)
    {
        discard;
    }

    return c;
}

And the ObserverWVP calculated in XNA

Matrix ObserverWVP = boneTransforms[mesh.ParentBone.Index] * worldMatrix // world
                        * Matrix.CreateLookAt(pos, pos + direction, Vector3.Up) // view
                        * Camera.Instance.ProjectionMatrix; // projection

Note that the direction vector is not normalized - it signifies the entire vector from the source (the character) to the outter edge of the arc.

I'm guessing the pixel shader is wrong. But I have no idea how to modify it. Any suggestions?


texts: Words to describe stat stacking behavior?

texts:
A character has a series of attributes.

Char {
    BaseStrength 1
    BaseHealth 100
    BaseLuck = 50
    BaseCharm = 20
}

and items will grant them modifiers

item0 {
  Modifier {
    Charm: + 1
  }
}

itemA {
  Modifier {
    Strength: ++ 1
  }
}

itemB {
  Modifier {
    Health: * 2
  }
}

itemC {
  Modifier {
    Luck: ** 1
  }
}

The way I was planning the operations + ++ * ** to work
was if a player has 2 of each type of item. it would stack as follows.

finalCharm = BaseCharm + item0.Charm (no stacking)

finalStrength = BaseStrength + itemA.Strength + itemA.Strength

finalLuck = BaseLuck + BaseLuck*(itemC.Luck + itemC.Luck)

finalHealth = BaseHealth + (BaseHealth * itemB.Health) + (BaseHealth * itemB.Health)

All except charm could be considered 'stacking' buffs.

itemA stacks additively, items B & C stack multiplicative.

How can I describe the stacking behavior differences between B & C to the player using words?


texts: How to morph a player character into another entity in MC JAVA 1.16-1.17?

texts: I want to add morphs into my game. Is there any command/code/resource I can use to make someone morph into an entity?


texts:
I'm using a geometry shader to generate polygons for my voxel terrain (marching cubes).  The data is output into a buffer using the method shown in the article I link to below.

http://msdn.microsoft.com/en-us/library/bb205122%28v=vs.85%29.aspx

Is there any way to somehow extract the vertex data from the buffer, sort of like the inverse operation of this?

struct Vertex
{
    float x, y, z;
    float tu, tv;
}

Vertex[] data = new[] // this is what I want to get
{
    ...
};

DataStream stream = new DataStream(bufferSize, true, true);
stream.Write(data);
stream.Position = 0;
buffer = new Buffer(device, stream, description);


texts: Good ways to edit arbitrary collision shapes for 2D physics engine?

texts:
Assume you have several 1024x1024 textures which contain an arbitrarily shaped and relatively complex cave system whose walls need to have collision polygons defined. The polygons need to be convex to work with the physics engine.

What kind of process and tools can you think of that would make editing the vertices of these walls as efficient and painless as possible? Especially considering that the polygons need to be convex, and the designer needs to see when that is not the case.


texts: Rotation about a point in OpenGL ES 2 (Android)

texts:
I'm trying to implement rotation about a point (the origin) using quaternions. My camera is at (0, 0, 3). I'm applying all the operations to the view matrix. Basically my rotation is at the moment not about the origin, but about the camera position. Here's what I'm trying to do:

public void rotate(float phi, float theta) {
        Quaternion phiRot = new Quaternion(0, 1, 0, (float)Math.toRadians(phi/2));
        Quaternion thetaRot = new Quaternion(1, 0, 0, (float)Math.toRadians(theta/2));

        Quaternion temp = thetaRot.mul(phiRot);

        camera.translate(0, 0, -3);
        camera.multiply(temp.toMatrix());
        camera.translate(0, 0, 3);
}

where

public void translate(float x, float y, float z) {
    Matrix.translateM(mViewMatrix, 0, x, y, z);
}

public void multiply(float[] matrix) {
    Matrix.multiplyMM(mViewMatrix, 0, matrix, 0, mViewMatrix, 0);
}

Any idea what I'm doing wrong?

EDIT: Solution that seems to work. Based off Milos' answer.

public void rotate(float phi, float theta) {
    Quaternion phiRot = new Quaternion(0, 1, 0, (float)Math.toRadians(phi/2));
    Quaternion thetaRot = new Quaternion(1, 0, 0, (float)Math.toRadians(theta/2));

    Quaternion temp = thetaRot.mul(phiRot);
    float[] rotate = temp.toMatrix();
    float transMinus[] = new float[16];
    float transPlus[] = new float[16];
    Matrix.setIdentityM(transMinus, 0);
    Matrix.setIdentityM(transPlus, 0);
    Matrix.translateM(transMinus, 0, 0, 0, -3);
    Matrix.translateM(transPlus, 0, 0, 0, 3);

    Matrix.multiplyMM(rotate, 0, transMinus, 0, rotate, 0);
    Matrix.multiplyMM(rotate, 0, rotate, 0, transPlus, 0);

    camera.multiply(rotate);
}


texts:
I'm trying to add networking functionality to my game. I want any user to be able to host the game, and anyone to be able to connect as a client. The client sends info to the host about their player's position, etc. When the host receives a message, it validates it and then broadcasts it to its other clients. I will primarily be dealing with UDP, but will also need TCP for chat & lobby stuff.

The problem is that I can't seem to get a packet sent from the client to the host or the other way around without enabling port forwarding on my router. But I don't think this is necessary. I believe the reason I need port forwarding is because I want to send a packet from 1 computer on a LAN to another computer on a different LAN, but neither of them have a global ip address since they're in a LAN. So really, I can only send packets targeting the other network's router, which must forward it on to the machine I want to reach. So how can I do this without port forwarding? Somehow a web server can communicate with my computer, which doesn't have a global ip, without port forwarding. And I've played plenty of multi-player games that don't require me to enable port forwarding. So it must be possible.

Btw, I'm using SDL_Net. I don't think this will change anything though.


texts: Is using an anonymous inner class to determine game item behavior the right way?

texts:
I'm developing a little game that has a bunch of different items. I categorize the items in separate classes (consumables, armor, weapons) that all extend Item.class. Then I use one main Items class where I basically initialize all items and give them their values and spritefile. I also want to give some items different behavior. For example a potion that teleports you or a potion that makes you stronger. I don't want to make separate classes for every item with different behavior so that's why I'm now thinking of using an anonymous inner class. The class will only be instantiated once.

This is what my simple Items class looks like:

public class Items implements Iterable<Item>{
    private static ArrayList<Item> items = new ArrayList<Item>();

    @Override
    public Iterator<Item> iterator() {
        return items.iterator();
    }

    public static Item getItem(int id) {
        return items.get(id).clone();
    }

    public static void initialize() {
        addItem(new Armor(0, 1, "Leather Helmet", "Leather_Helmet.png", 30));
        addItem(new Consumable(1, 16, "Apple", "Apple.png", 30));
        addItem(new Consumable(2, 1, "Strength Potion", "Strength_Potion.png", 0) {
            @Override
            public void consume(Player player) {
                // Do potion stuff
            }
        });
    }

    public static void addItem(Item item) {
        items.add(item.getId(), item);
    }
}

The initialize() method is basically where I load in all the different items to the game. The third item is where I use an anonymous inner class. Is this the "right" way of handling things? Let me know how I could handle this differently.


texts: How do I trigger just once and not multiple times if I the Player enters the Trigger?

texts:
I wanna trigger just one time and not multiple times. I have a Health System and I want that the Player takes damage from an GameObject if he enters the Trigger but it directly triggers like 65 times in a sec. how can I trigger just once ?
I dont have a Script attached to the GameObject what should give the Player Damage, it just have a Box Collider 2D. The Code for the Trigger enter has the HealtScript that is attached to the Player.

Here is my HealthScript

public Image Bar;
public float maxHealth = 100f;
public float currentHealth = 0f;

// Use this for initialization
void Start ()
{
    currentHealth = maxHealth;
    InvokeRepeating ("decreaseHealth", 0f, 2f);
}

void decreaseHealth()
{
//  currentHealth -= 5f;
    float calchealth = currentHealth / maxHealth;
    SetHealth (calchealth);
}

void SetHealth (float myhealth)
{
    Bar.fillAmount = myhealth;
}

void OnTriggerEnter2D (Collider2D other)
{
    if (other.gameObject.tag == ("Damage"))
    {
        currentHealth = -5f;
    }
}

}


texts: How Could I accommodate Gender Fluid Players In My Game

texts:
I'm world building for a fantasy MMORPG and I really want to have a safe and acceptable environment for all possible players. Of course I am going to be realistic and have prejudice in game, it wouldn't be believable if everyone got along. However I personally feel that if a paying consumer of my game feels like having a non binary character, why should I limit them and make them feel uncomfortable? They could always make two separate characters, but then there's a lack of sync and feeling that they are one person. My team also discussed having a feature that switched between avatars while keeping gear and skills. Another idea was a sort of illusion spell that would alter the players body to a set form based off of their original facial shape and general traits. I would like to hear more suggestions and thought of this topic in games, or if something like this has been done before, even if it was not intended for gender fluid people.
In the end I would like to have a believable way for a player to switch between male and female in game.

Previous Comments

Do characters in the game have the possibility to beget offspring (male) or to give birth to offspring (female)? Otherwise, they are not male and female, but rather masculine and feminine: which is a much simpler problem, and one that should have minimal impact, if it has any impact at all. Actually, what exactly would be the impact of switching the identifier of a character from Cao Pi to Guo Nüwang? (One of those names is feminine, and the other masculine; which is which is left as an exercise.)

We are working on a function for players to have NPC children. So if they had gotten pregnant they would not be able to change the sex of their avatar, that would cause problems. This is more of gender and appearance, not so much biological sex. Though I guess it would be plausible for them to be pregnant, and then get some one else pregnant after giving birth. If of course it wasn't illusion magic.

It seems like you already know your answer. If it's about gender and appearance, then it's about how a character is physically portrayed. Right? So for example, in an typical MMORPG, you purchase a breastplate from the local armory, you'll have a 'male' version and a 'female' version. Perhaps just give an option to purchase a variety or degree of masculine and feminine armor regardless what biological sex your player is. For example, a male player can purchase a very feminine looking breastplate.

we have plenty of possible answers. It's more of what would make people feel most comfortable. A lot of gender fluid people can have body dysmorphic disorder, and some of them play games for gender comfort. It's like a self applied therapy where you can be what ever you identify with, and others will see and accept you as that gender. So masculine and feminine armor would work and is probably an idea we will use, we don't want someone to feel confined to one gender. Especially because gender fluid people can change from masculine to feminine day to day. the armor also means they may have to buy multiple sets. also some one may feel strongly masculine one day, and strongly feminine another, making a gender ambiguous character a bit awkward.


texts: procedurally combine a main character with weapons during animations

texts:
I need to find a way to programmatically place weapons for main character in right position of his body.

For example if I am using UMA to procedurally create humans and then use some pre-existing models of guns (10-20) of them. Now I need to find a way to place them correctly in the hand positions of the human model. I will use mixamo or IK to apply animations on the human character.

But is there any way to programmatically place the objects in the right positions? Probably by marking some joints?

I am looking at some efficient approach to begin with on this.


texts: Implementing reference counting from scratch or using shared_ptr for resource?

texts:
In an OpenGL application that I am writing, I want to have a simple shader class to wrap the OpenGL shader handle. Ultimately, I want this shader class to behave very similarly to a shared_ptr in c++ (that is, keep a reference count and free the resource when no references are left). While it is relatively trivial to implement this reference counting from scratch, I was wondering if it is considered a better design choice to instead use std::shared_ptr with a custom deleter to free up the resource.

The main source of my doubt is the fact that it might be considered unconventional due to the fact that (as far as I know), creating an OpenGL shader program handle does not actually involve heap memory (which is what shared_ptr takes care of) but I still feel that it could apply here because I want this resource to be handled very similarly to how heap memory would be handled. The purpose of this question is basically to seek the opinion of others as to whether this actually is unconventional, because I do not know.

Also, although I used shaders as an example, the same question also applies to textures and buffers in OpenGL as they also must be allocated and freed.


texts: How do I manually control the lifetime of actor objects in C#?

texts:
I have the following Actor and Scene classes :

public class Actor
{
    string name;
    vec3   position;
    quat   rotation;

    public void Update()
    {
        ...
    }

    public void Render()
    {
        ...
    }
}

public class Scene
{
    List<Actor> actors = new List<Actor>();

    public void OnUpdate()
    {
        for (int i = 0; i < actors.Count; i++) {
            actors[i].Update();
        }
    }

    public void OnRender()
    {
        for (int i = 0; i < actors.Count; i++) {
            actors[i].Render();
        }
    }

    public void DestroyActor(Actor act)
    {
        actors.Remove(act);
    }
}

The DestroyActor method will remove a specified actor from the list, and stop it from updating/rendering, but it does not destroy it. Other actors still have a reference to that object, for example, the camera has reference to the player actor to chase him:

public class Camera
{
    Actor player;

    public void Update()
    {
        if (player == null) {
            // select nearest NPC and chase him
        } else {
            // chase player
        }
    }
}

I can change the classes and make them communicate via handles, for example, but that means I have to make the Actor class internal, instead of public, and include methods such as ActorExists(int hdl), GetActorPosition(int hdl) and GetActorRotation(int hdl). This makes me wonder what the difference is between C# and a low level language, like C.

In the Unity game engine, a call to MonoBehaviour.Destroy(player) will completely destroy the object, and set all references of that object to null. I know that they use the embed mono, and have more control over how the garbage collect works, but I wonder how do others work around these kind of problems in C#?


texts:
I just recently started using C++ and OpenGL and I am running into an issue. I am not totally sure what I am doing so could you please tell me what I am doing wrong and what I could improve?

Here is the problem:
I can't see to get a textured quad to render at all. I've tried a bunch of different ways and even asked people who claimed to know C++ and they said they didn't see any obvious issues.

I am using the following libraries:

GLFW (For input/window callbacks)
GLUT (For OpenGL)

Here is my code:

///In class "Game"

    virtual void render() {

        int ww, hh;
        glfwGetWindowSize(gameWindow, &ww, &hh);

        glLoadIdentity();
        gluOrtho2D(0, ww, hh, 0);

        glClearColor(0, 0, 0, 1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        gameRoom->render();

        glfwSwapBuffers(gameWindow);

        glPopMatrix();

    }

///In class "Sprite"

    void render(int index, int x, int y, float xscale, float yscale)
    {
        float tcx1, tcx2, tcy1, tcy2;

        tcx1 = (float)frames[index].x / base_width;
        tcx2 = (float)(frames[index].x + frame_width) / base_width;

        tcy1 = (float)frames[index].y / base_height;
        tcy2 = (float)(frames[index].y + frame_height) / base_height;

        float vx1, vx2, vy1, vy2;

        vx1 = (x - Game::gameView->x) / Game::gameView->width;
        vx2 = (x + frame_width * xscale - Game::gameView->x) / Game::gameView->width;

        vy1 = (y - Game::gameView->y) / Game::gameView->height;
        vy2 = (y + frame_height * yscale - Game::gameView->y) / Game::gameView->height;

        glPushMatrix();

        glBindTexture(GL_TEXTURE_2D, texture);
        glEnable(GL_TEXTURE_2D);
        glBegin(GL_TRIANGLES);

        glTexCoord2f(tcx1, tcy1); glVertex2f(vx1, vy1);
        glTexCoord2f(tcx2, tcy1); glVertex2f(vx2, vy1);
        glTexCoord2f(tcx1, tcy2); glVertex2f(vx1, vy2);

        glTexCoord2f(tcx2, tcy1); glVertex2f(vx2, vy1);
        glTexCoord2f(tcx1, tcy2); glVertex2f(vx1, vy2);
        glTexCoord2f(tcx2, tcy2); glVertex2f(vx2, vy2);

        glEnd();
        glDisable(GL_TEXTURE_2D);

        glPopMatrix();

    }

When I run the game all I get is a black screen... Please help!


texts: Unity - plain material colour darker than expected

texts:
I want to add to scene object without textures, only plain material, here is my import flow:
I create object in Sketch and export to SVG:

Then I import SVG to blender (Material do not use nodes, has plain color #96DFE4) and export it to FBX.
Then I import FBX to unity, as you can see material colour is much darker than SVG created:

The only Lighting source I use is Ambient with colour white and Intensity 0.
How to render object with exactly same material colour as SVG? I don't want any shadows etc, just plain color.


texts: How to implement a Behavior Tree (preferably in Unity 3D)

texts:
I have a state machine I want to implement as a behavior tree. I now have an understanding of how they work but I can't seem to find a full implementation of one. I have implemented a simple one using a plug-in called Behavior Machine but the problem I have with it is I feel like it limits me just as it did when I used it for making my FSM until I implemented my own FSM that is when I had the privilege of using my own functions to trigger my own state transitions and optimize it so that it doesn't use a lot of resources.

The other problem I have is it is difficult to implement my own nodes and control which part executes (optimization). Any idea where I can find a good tutorial on how I can do this, preferably with Unity and in C# or Java. Or where I can find a good library with proper documentation because the one I found on Git-hub or other sites are buggy or just some classes with no documentation. Your help will be greatly appreciated.

So basically, what I want to do is implement my own Behavior Tree. This way I think I can have better control on how it executes so that it can run on mobile devices smoothly.


texts: How to handle loading and keeping many bitmaps in an Android 2D game

texts:
In an Android 2D game which is using SurfaceView where its onDraw is driven by a loop from a Thread, I use many bitmap sprites (sprite sheets) and two background size bitmaps, which are all loaded into memory at the start.

It all works fine, however, when the activity is onPause or after reloading it few times, Android shows a tendency to wipe out the big bitmaps only, probably to free memory. Sometimes this happens even in the middle of loading this very activity.

In order to counter this, I made a check in the onDraw method to test if the big bitmaps are still there and reload them if they are forcefully recycled by Android, before drawing them on Canvas.

This solution may not be the most stable, and since I know that there are much more accomplished android game programmers here than myself, I hope you can reveal some tricks or secrets or at least provide some good hints, how to overcome this.


texts: How to adapt background image size with player score?

texts:
I have an image and a text for displaying the player score. They are both displayed through a canvas.

Currently, my textbox remains the same size independent of the score, so when the player gets a big score, it prints outside of the image.

I want keep my score inside the background image, and I also want to change the size of the image along with the number of digits in the score, like "10, 100, 1000, 10000" etc.

How can I adapt the size of my background image on the amount of digits in the current score?


texts: Sampling procedural texture generated in shader?

texts:
We have a custom Unity surface shader which generates some procedural patterns.

However we are getting very bad moire effects when the pattern frequency is too high (made worse by distance, surface angle).

I would like to apply some kind of blur on the texture to reduce this moire effect. All of the shader blur examples I can find rely on sampling surrounding pixels from the texture bitmap.  Since we've generated the pattern procedurally per pixel, such a bitmap doesn't exist.

Does anyone know how we might introduce some kind of blur effect in this case, to reduce the moire?

Thank you.


texts: SWiSH alternative Flash animator for AS3

texts:
In the past I've used SWiSH to create small animations that I could use for Flash projects, however, I'm now trying to move to writing AS3 which SWiSH doesn't support.

Whilst I have access to Flash CS5 through work, it doesn't have much in the way of in-built effects & animations, compared to SWiSH's 400+, and I want to be able to create various effects quickly and easily. (I'm a coder, not a graphics kind of guy!)

So, does anyone know of a good alternative to SWiSH (Flash Animator) that I could get/purchase that has a lot of stock animations/effects built into it, but is fully compatible with AS3, allowing me to export symbols in SWF and embed/use them in FlashDevelop?


texts: I'm trying to add portals to a game (as in the entities from the Portal video game), and I've gotten them to a render the other portal's pos/dir to a texture which I can then display on a surface. However, I'm not really sure which direction to render the portal view from so that it'll actually look like a portal. Simply rotating the camera dir by the difference between the portal dirs isn't correct.


texts: How to find the "up" direction of the view matrix, with GLM

texts:
Using OpenGL and the GLM matrix library, I want to translate my camera relative to the world coordinate system. This requires me to compute the necessary view matrix. To initialise the view matrix, I used:

view_matrix = glm::lookAt(eye, centre, up);

Where eye = (0, 0, 10), centre (0, 0, 0), and up = (0, 1, 0). Suppose I want to now translate the view matrix by 5 unites in the camera's y-direction, i.e. to move upwards relative to the model. I tried:

view_matrix = glm::translate(view_matrix, glm::vec3(0, 5, 0));

This works fine at first, because the view and world coordinate systems are aligned. However, if I then rotate my camera a bit, and then perform this translation, it no longer works. Instead, it moves the camera along the world coordinate system, rather than the camera coordinate system.

So what I need to do, is to find the vector which represents the "up" direction of the camera, and then translate along this vector. This is similar to the inverse of the glm::lookAt(eye, centre, up) function.

In summary: Is it possible to find the "up" vector of the view matrix using the GLM library?


texts: Why do games dynamically link to the CRT?

texts:
Almost all big titles that I have played require you to install the MSVC runtime. There have been numerous questions about "statically vs. dynamically linked CRT" on StackOverflow, the reasons for dynamic CRT generally boil down to:

Reduced memory usage if other programs are using the same libs
Can update the libraries independently.

But I wonder, how often are these reasons related to game development?

Most games spend at least a hundred MB of RAM and it's not like saving some KBs really matter. Besides, games are supposed to capture the user's sole attention so he'll probably not be running other programs to share the CRT.
I don't think I have seen a game needing to upgrade its CRT in its life-cycle.

So, why don't games statically link their CRT so they can reduce the extra step of installing MSVC runtime?


texts:
I am making an open world 3d platformer in Ogre3D, and I have no idea on what kind of 3d map file format I should use for it.

I want to make low-polygon blocky-style objects. Probably rectangles and other geometrical figures that don't have circular edges. Some of those blocks will have properties, like climbable or they might move.

I was wondering what would be the best thing to do to make the map (just one level, as it is open).


texts:
I’m stuck in understanding of usable actors from survivable c++ example.
I have return Cast<AUsableItem>(Hit.GetActor());.
I have class AUsableItem. And I have another class AUsableWeapon inherited from AUsableItem.

I have function Use() in both classes, so basically in the end it looks like Cast<AUsableItem>(Hit.GetActor())->Use(). Hit.GetActor() returns instance of AUsableWeapon. And when i do that ->Use() call, it goes into AUsableWeapon even though it was casted to AUsableItem. Problem is - I cant understand how exactly after casting to AUsableWeapon I get Use() called from AUsableWeapon.


texts: Is Test Driven Development viable in game development?

texts:
As being Scrum certified, I tend to prone for Agile methodologies while developping a system, and even use some canvas from the Scrum framework to manage my day-to-day work.

Besides, I am wondering whether TDD is an option in game development, if it is viable?

If I believe this GD question, TDD is not much of a use in game development.
Why are MVC & TDD not employed more in game architecture?

I come from industrial programming where big projects with big budgets need to work flawlessly, as it could result to catastrophic scenarios if the code wasn't throroughly tested inside and out.

Plus, following Scrum rules encourages meeting the due dates of your work while every single action in Scrum is time-boxed! So, I agree when in the question linked above they say to stop trying to build a system, and start writing the game. It is quite what Scrum says, try not to build the perfect system, first: make it work by the Sprint end. Then, refactor the code while working in the second Sprint if needed!

I understand that if not all departments responsible for the game development use Scrum, Scrum becomes useless. But let's consider for a moment that all the departments do use Scrum... I think that TDD would be good to write bug-free code, though you do not want to write the "perfect" system/game.

So my question is the following:

Is TDD viable in game development anyhow?


texts: Problem with transparent textures in SFML

texts:
I have been told that this is kind of a common problem with transparent textures, but didn't get any further information on how to solve it.

In my code, I'm trying to render this texture (a square with rounded corners, where rounded corners have some alpha)

What I get instead is this

Notice those greyish places on the corners of the textures - where rounded corners are supposed to be.

What could be causing this? I have a pure-white texture, so I don't expect a single pixel to get any darker than the background. All pixels should have at least the color of background, but as you can see, there is something darker.

Zoomed even more:

Any help would be highly appreciated.


texts: Unity 2019 Error : com.unity.xr.arsubsystems@2.2.0-preview.3/Runtime/ImageTrackingSubsystem/XRImageTrackingSubsystem.cs57,30): error CS0506:

texts:
I am opening an old project created in 2019.3 inside my new Unity 2019.4.  I got this error message in Unity Console:
Library/PackageCache/com.unity.xr.arsubsystems@2.2.0-preview.3/Runtime/ImageTrackingSubsystem/XRImageTrackingSubsystem.cs(57,30): error CS0506: 'XRImageTrackingSubsystem.Destroy()': cannot override inherited member 'Subsystem.Destroy()' because it is not marked virtual, abstract, or override

Please note that this current project does not use anything related to AR "Augmented Reality" or XR package.
I have already Googled this error message, but have not seen a solution yet.
However, I guess that this error likely comes from some conflicts in the AR or XR versions.
To fix this error, should I install or update the basic Unity XR or AR package ?
Thank you very much.


texts: Frustum Culling: How to calculate if an angle is between another two angles

texts:
I am trying to implement frustum culling but got stuck on how to determine if the angle that the object is from the player is in the FOV of the player. So basically I have the following information:

FOV
Player's 3D position (x1, y1, z1)
Object's 3D position (x2, y2, z2)
Player's turning angle with turning left being positive and right negative

How do I determine if the player should be rendered (in the player's field of view) or not?

I tried using this, but it will cull at certain player turn angle and not work in other player turn angle. Ex, work at 0 - 90, but doesn't work at 90 - 180.

    float turn = player.getTurn();
    float FOV = this.FOV;
    if (square(entity.getPosition(), player.getPosition()) < FAR_PLANE / 6) {
        double playerz = player.getPosition().z * -1;
        double playerx = player.getPosition().x;
        double entityz = entity.getPosition().z * -1;
        double entityx = entity.getPosition().x;
        double degrees = Math.toDegrees(Math.atan((playerz - entityz)
                / (playerx - entityx)));
        double sinfz = Math.asin((playerz - entityz)
                / square(player.getPosition(), entity.getPosition()));
        double cosfx = Math.acos((playerx - entityx)
                / square(player.getPosition(), entity.getPosition()));
        /*
         * if(sinfz > 0 && cosfx > 0) degrees = degrees; else
         */
        if ((entityz - playerz) > 0 && (entityx - playerx) < 0)
            degrees = 180 - Math.abs(degrees);
        else if ((entityz - playerz) < 0 && (entityx - playerx) < 0)
            degrees = Math.abs(degrees) + 180;
        else if ((entityz - playerz) < 0 && (entityx - playerx) > 0)
            degrees = 360 - Math.abs(degrees);
        if(betweenAngle(90 + turn - FOV / 2, (float) degrees, 90 + turn + FOV / 2))
            return true;
    }
    return false;


texts: What is a good way to load and provide graphics to classes and subclasses in monogame?

texts:
First of all: I'm not sure if my question is worded well, I just can't think of any better way. I'm also a beginner both at Monogame and programming in general, so my question might miss the actual issue or be based on incorrect assumptions / understanding regarding the topic.

Assuming the following simplified example: a 2D-game in Monogame with a base class Object, derived classes StaticObject and MobileObject and derived from the later the classes Human and Orc.

What is a good way of handling graphics (in the form of several sprite sheets) in this construct? What I can come up with:

a) non-static Texture2D => every instance carries around it's own copy of the sprite sheet, which sounds like a huge waste of resources if, e.g. i have a sprite sheet for 100 different StaticObjects, and a screen  with 10 stones and 15 logs on it then has the memory footprint of 25 full sprite sheets, when either one sheet or even just 2% of one sheet would be enough.

b) static Texture2D => all draws from just one sprite sheet, but I don't know how I would deal with having different sprite sheets (after all, they are all the same reference now), and I would rather not put all graphics for all different object classes into just one sprite sheet

c) have a separate (static?) class that houses all the graphics and have all my objects get their graphics from that class => ??

Could anybody point me in the right direction? (Or tell me if I'm going the wrong way all together)
Maybe this is also a quite common subject and I just google for the wrong terms, in which case just telling me what to look for would also be great.

Thanks!


texts: GL_TEXTURE_MAX_LEVEL equivalent on DirectX

texts:
I'm trying to mix atlas and mipmapping for a kind of Minecraft editor I'm doing. Everything looks good until I reach the smaller mipmaps of the atlas texture, where obviously all the textures are mixed into one, looking horrible at the distance.

With OpenGL I'd use glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, n); to avoid this problem, but I'm unable to find the DirectX equivalent. Is it possible to do this in DirectX?

Thanks in advance


texts: How do I generate paylines and pay dots for a slot game?

texts:
I'm working on a HTML5 slot game and am completely stuck on the pay lines and the dots that produce the lines from 1 end to the other.

What's the logic behind generating a random number of dots (9-30) and then paylines properly? Paylines shouldn't overlap each other. Similarly paydots shouldn't overlap and position themselves properly. On a small mobile screen 30 dots should just fit fine.

Then, how can I go about matching combinations from reels against the paylines?


texts: Implementing proportional navigation in 3D

texts:
Good afternoon guys,

a = N * λ' * V

is the formula for the commanded acceleration required to hit the target,
where N is the proportionality constant, λ' is the change in line of sight and V is the closing velocity.

Data I natively have:

[x,y,z] position of both missile and target;
[vx,vy,vz] velocity vector of both missile and target;
[x,y,z] vector which points from missile to target and opposite;
This is set by me but still: maximum speed of missile.

Data I can get with some calculations:

Vertical angle between missile and target (and opposite)  ;
Horizontal angle between missile and target (and the other way around).

That's the reference system of the game:

λ' or the derivative with respect to time of the Line of Sight it's a concept I really didn't understand...  its unit should be, in theory, Hz or (s^-1) since m/s^2 = λ' * m/s -> λ' = 1/s
V should be pretty easy to calculate: V = v(missile) - v(target) OR
Vx = (v(missile) - v(target)) * cos (x0y)
Vy = (v(missile) - v(target)) * sin (y0z)
Vz = (v(missile) - v(target)) * cos (y0z)
N well it's a scalar number, usually 3.

The computed acceleration will then be passed to a RK4 integrator which will move the interceptor towards its target.
To steer the missile, I will simply change its velocity vector at every update (every 1/60th of a second) and its orientation accordingly. For example: if the missile has a velocity of [0,100,0], he's going 100 m/s due y+ axis. If at the next frame it should slightly turn right, then he'll be going to have a velocity of [10,99,0] and so on.

That's the only thing left to finish off my little thesis and unfortunately I'm stuck here. In the meantime,  thank you very much!

Here's a video I made, but it doesn't still actually use the Proportional Navigation law: it checks if the missile is "aligned" to its target and eventually correct its route.
That's my actual code: pastebin

That's what i've come up with but sadly doesn't work as expected:

params ["_n","_missile","_target"];
private "_a";

_vm = velocity _missile;
_rm = getPosASLVisual _missile;

_vt = velocity _target;
_rt = getPosASLVisual _target;

_vr = _vt vectorDiff _vm;
_r = _rt vectorDiff _rm;

_omega = (_r vectorCrossProduct _vr) vectorMultiply (1/(_r vectorDotProduct _r));

_a = (_vr vectorCrossProduct _omega) vectorMultiply _n;

_a

Similar questions:
Finding the components of Proportional Navigation in 2D


texts: Implementing an efficient method of server-side checking

texts: I'm making a web-based action RPG game. I don't want players to cheat, but I also don't want the game to constantly pause to wait for the server to respond. I made it so the game is played on the client-side (for responsiveness) and the server does routine checking to validate the game state. But the system is very cumbersome. The server has to calculate every single frame and compare the entire game state to the game state sent from the client. If anything in the game states are different form each other, the server kicks the player off. However, this means the game has to send 30 requests a second, and the server must calculate it all in time. If many people are playing the game, I don't think my one free Heroku dyno can handle that. How do I implement an efficient and elegant way of validating players' moves on the server side?


texts:
I’m developing a little 3D game to improve my Unity C# development.
However, I am faced with a recurring error that I cannot find the solution to :/
In fact, I always get the error Nullreferenceexception: Object reference not set to an instance of an object when I want to create a new Gameobject in my scene.

I wish I could spawn a bonus based on a percentage of chance when an enemy is killed.

So I created a Bonus mother class and a Bonushealth daughter class. So Bonushealth inherits the Bonus methods.

Here’s the mother class code (Bonus) :

using UnityEngine;

public class Bonus : MonoBehaviour
{
    protected int lifeTime;

    public int LifeTime { get => lifeTime; set => lifeTime = value; }

    protected void RandomDropBonus(Transform posEnemy)
    {
        int chance = Random.Range(1, 100);

        switch (chance)
        {
            case int n when (n <= 100):
                Instantiate(Resources.Load<GameObject>("bonus"), new Vector3(posEnemy.position.x, posEnemy.position.y, posEnemy.position.z), Quaternion.identity);
                break;
        }
    }

    public void RandomBonus(Transform posEnemy)
    {
        int rdn = Random.Range(1, 1);
        Debug.Log(rdn);

        if(rdn == 1)
        {
            RandomDropBonus(posEnemy);
        }
    }
}

Here's the daughter class code (BonusHealth) :

using UnityEngine;

public class BonusHealth : Bonus
{
    public GameObject prefabHealth;
    // Start is called before the first frame update
    void Start()
    {
        LifeTime = 10;
    }
}

I call the RandomBonus() method when an enemy is killed (in the Enemy class), Here's is the code :

private Bonus bonus;
bonus.RandomBonus(this.transform);

if I make Bonus bonus = new Bonus()
I always get this error : ArgumentException: The Object you want to instantiate is null.

In my prefab folder is contained my bonus prefab named bonus. I added the Bonushealth script on it.

I did a lot of research on the Internet but no way to find a solution :/

Thanks in advance ;)


texts: How can I detect when the player or any object that is moving is touching or entered a drawn linerenderer circle radius area?

texts:
In the screenshot, the object that is in the center and the circle is drawn around is the small spaceship.
What I'm trying to do is when the player or any object that moves towards the circle if the object touch or better if the object enters the circle area then do something.
For example, the cube in the screenshot is inside the circle area then do something like ontriggerenter and if the object moves out do something like in ontriggerexit. The same idea.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[ExecuteAlways]
[RequireComponent(typeof(UnityEngine.LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    [Range(1, 50)] public int segments = 50;
    [Range(1, 500)] public float xRadius = 5;
    [Range(1, 500)] public float yRadius = 5;
    [Range(0.1f, 5)] public float width = 0.1f;
    [Range(0, 100)] public float height = 0;
    public bool controlBothXradiusYradius = false;
    public bool draw = true;

    [SerializeField] private LayerMask targetLayers;
    [SerializeField] private LineRenderer line;

    private void Start()
    {
        if (!line) line = GetComponent<LineRenderer>();

        if (draw)
            CreatePoints();
    }

    private void Update()
    {
        if (Physics.CheckSphere(transform.position, xRadius, targetLayers))
        {
            Debug.Log("player detected");
        }
        else
        {
            Debug.Log("player NOT detected");
        }
    }

    public void CreatePoints()
    {
        line.enabled = true;
        line.widthMultiplier = width;
        line.useWorldSpace = false;
        line.widthMultiplier = width;
        line.positionCount = segments + 1;

        float x;
        float y;

        var angle = 20f;
        var points = new Vector3[segments + 1];

        for (int i = 0; i < segments + 1; i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;

            points[i] = new Vector3(x, height, y);

            angle += (380f / segments);
        }

        line.SetPositions(points);
    }

#if UNITY_EDITOR
    private float prevXRadius, prevYRadius;
    private int prevSegments;
    private float prevWidth;
    private float prevHeight;

    private void OnValidate()
    {
        if (!line) line = GetComponent<LineRenderer>();
        if (!line) return;

        if (!draw)
        {
            line.enabled = false;
        }
        else
        {
            line.enabled = true;

            if (xRadius != prevXRadius || yRadius != prevYRadius || segments != prevSegments || width != prevWidth || height != prevHeight)
            {
                CreatePoints();

                prevXRadius = xRadius;
                prevYRadius = yRadius;
                prevSegments = segments;
                prevWidth = width;
                prevHeight = height;
            }

            if (controlBothXradiusYradius)
            {
                yRadius = xRadius;

                CreatePoints();
            }
        }
    }
#endif
}

I tried inside the Update to do :
if (Physics.CheckSphere(transform.position, xRadius, targetLayers))
        {
            Debug.Log("player detected");
        }
        else
        {
            Debug.Log("player NOT detected");
        }

but it's not working even if I change in the Inspector the targetLayers to the player layer.
The player is not the cube in the screenshot and the player have a collider but the drawn circle don't have a collider.  not sure how to do it with the Physics.CheckSphere or some other way but the idea is when the player or any other object enter the drawn circle area do something. maybe some how to calculate the distance from the circle ? not sure how to do it.


texts: How to make a class diagram and data model of a Unity3D game?

texts:
I'm developing a 3D platformer video game on Unity3D and I've been asked to present its UML class diagram and data model. If I'm not mistaken Unity uses an entity-component-system, which necessarily doesn't use heritage. How would a class diagram from a Unity game look like, in that case?

Also, I've been taught that usually data model refers to entity-relationship-models that represent a database. In the case my game doesn't use a database, how could I diagram the way the player's data is store on the game? I'm storing the player progress on a file in the user's computer.


texts: How to take input from featured mobile phone in cocos creator?

texts:
I am beginner to cocos creator and I came to know cocos has Keyboard,DeviceMotion and Mouse input event but I want to know how to take input from featured mobile phone having number pad?

Will it be similar as taking input from keyboard as number or there is something else.


texts: Unity3d iOS: unable to find iPhone_GlesSupport.h

texts:
i've an old unity project and i've tried it just today (with unity 4.1) and xcode 4.6.
Xcode is unable to build it for the error: "iPhone_GlesSupport.h" file not found.

Im pretty a noob under xcode and objective-c in general so i've searched in internet about this problem, but without any luck.

Anyone know more or have experienced this problem?

Thanks


texts: My game is not shown in Play Market New Releases

texts:
I've published my app for like an 36 hours ago. It is possible to find it with exact search query ("Village Keeper") and it is available via the direct link.

Thing is I can't find it in "New Releases" ("New Free Games") and I can't find it by typing something like "village game" or "keeper". So I have only 3 installs by me and my friends.

Is it a bug or is a new app not guaranteed to get in "New Releases"? I tried to google it but found no answers. If so, how can indie developer get into the market with no money for an ad campaign?

P. S. I tried to contact Google Support twice and 24 hours after first email passed with no reaction.


texts:
How  to render metaballs?
I am a Python programmer familiar with the Panda3d and Blender3d APIs. My math kinda sucks, but I know enough to write game logic code and procedural model generation code, as well as importers/exporters for the 3d modeller Blender. So you kind of get my level of experience. So can anyone explain or link to a tutorial which explains what needs to be done, without advanced math or with mentioning what math concepts are needed?

This is what I want to achieve:

http://www.youtube.com/watch?v=dEipENLes10
http://www.dailymotion.com/video/xn3xfn_mercury-meltdown-psp-un-trailer-pour-mercury-meltdown_videogames?search_algo=2

Though with probably more metaballs on screen at the same time.


texts: Best way to Draw a cube for 3D Picking on a specific face

texts:
Currently I am drawing a cube for a game that I am making and the cube draw method is below.  My question is, what is the best way to draw a cube and to be able to easily find the face that the cursor is over?  My draw method works just fine, but I am getting ready to start to add picking (this will be used to mold the cubes into other shaps), and would like to know the best way to find a face of the cube.

public void  Draw() {
    // center point posX, posY, posZ
    float radius = size / 2;

    //top
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,0.0f,0.0f); // red
            glVertex3f(posX + radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY + radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //bottom
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,1.0f,0.0f); // ?? color
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

    //right side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(1.0f,0.0f,1.0f); // ?? color
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

    //left side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,1.0f,1.0f); // ?? color
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //front side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,0.0f,1.0f); // blue
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
        }
    glEnd();
    glPopMatrix();

    //back side
    glPushMatrix();
    glBegin(GL_QUADS);
        {
            glColor3f(0.0f,1.0f,0.0f); // green
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();
}


texts: How can I draw a specific GameObject into a texture in Unity?

texts:
I need to draw only a few specific objects into a texture (with their material) and then use that RenderTexture as a texture for an another object. I think Graphics.DrawMesh() and Graphics.SetRenderTarget() would be helpful, but I'm not sure.

Ultimately I'm trying to create refractive water, which will refract only specified GameObjects, not layers. How can I do this?


texts: How are character creators/customizers done in other games?(Reference images inside)

texts:
Possible Duplicate:
What techniques could I use to give players the ability to control certain features, e.g. fatness?

How are character creators(usually seen in RPGs) done?
Such as, the ability to change almost anything on the character, ranging from the size of the nose to overall height.
Sims also has a fairly indepth one, but I can't find a good screenshot of it.
Do they just store a lot of sub-objects for the body and scale them based on preferences? How would that affect things such as animation, and texturing?


texts: How to move Objects smoothly like swimming arround

texts:
I have a Box2D project that is about to create a view where the user looks from the Sky onto Water. Or perhaps on a bathtub filled with water or something like this. The Object which holds the fluid actually does not matter, what matters is the movement of the bodies, because they should move like drops of grease on a soup, or wood on water, I can even imagine the the fluid is mercurial, extreme heavy and "lazy".

How can I manipulate the bodies (every frame or time by time) to make them move like this?

I started with randomly manipulation their linear velocity, but I turned out that this not very smooth and looks quite hard.

Is it a better idea to check their velocity and apply impulses? Is there any example?

Greetings philipp


texts: Real life example of an agile game development process outputs

texts:
I'm trying to learn about applying agile methodologies to game development. But seems to be impossible to find real life examples.

There seems to be plenty of material discussing how 'in principle' agile is applied to a game. But that is NOT what I am looking for. I have the Keith book.

What I AMlooking for are real EXAMPLES of things like;

Initial user stories
Final user stories (complete, covering the entire game requirements)
Acceptance criteria
Task list
Sprint backlogs (before and after each sprint)

The agile books seem to have some limited examples, many of which seem contrived or limited. In this era of open source software,  there must be a publicly available documented example of the process applied to a real game.

I am asking specifically about games because they are so different from normal applications. Regular applications are built to all users to complete specific tasks in order to get stuff done(book a room, print a report etc). People play games for much less tangible reasons, so I think the process is significantly different.

[it doesn't have to be scrum, it could be any process, just needs to be a real life example game and be reasonably complete]


texts: How to create a minecraft style world that is based of a heightmap

texts:
For my game I am trying to create a Minecraft style world that is based off a heightmap that I made In Photoshop. I am trying to make the map which is 7km squared where each cube is 1m cubed but I haven't found a way to do it. The heightmap converts to a terrain file(in unity), but my problem is that I can't create the Minecraft look.

what I have done so far looks like this

what i want looks like this


texts: Apply new default transform values for gameobject

texts:
I'm not sure if the title is correct. But how does one go about the following:

I imported a mesh created in blender.When i import the object it is at the desired rotation and scale, however, when i look at the properties of the transform the scale is 100 and the rotation is 89.9123xxxxxxx.

Is there any way i can rotate it to the desired rotation, scale it to the desired scale then tell unity that it should update the prefab and set this new rotation as 0,0,0 and the scale as 1,1,1.

Reason behind this, is i am tiling a few prefabs, and the rotations are being used.... after a couple of hundred tiles, there are floating point errors.


texts: Creating Top-Down Race Track From A List Of 2D Points

texts:
My final year project for university is based on the idea that a two-dimensional top-down multiplayer racing game can be made using Google Maps to dynamically generate race tracks. The idea is that the user would pick two points on a Google Map and then click a button that would generate a route between the two points.  I am able to extract the path from these points.

Now, I can't figure out how to actually transform this shape into a race track. I tried changing the stroke width, it messes up the details, like curves.

I want thicker strokes without losing details and the strokes overlapping each other so that the strokes look more like race tracks, because the camera would center the player's car and be zoomed in on it while following the car. Something like this:

Is there any way I can make the route shape into an actual race track? If so, how?


texts: How to import .fbx MODEL into Unity Project?

texts:
I created new Project in Unity. I downloaded .fbx file from internet, it looks like as give in image.
How can I import .fbx into Unity Project. I am beginner and this is my first Unity Project.

Thanks


texts: Animated Typing Memory Usage with Immutable Strings

texts:
Right now I'm programming a game that has an animated typing effect typically seen in older 1980's and 90's role-playing games. An example can be seen here.

The typing effect is generated by taking a target string and rendering a substring of it each frame. The length of the substring is initially zero, but it is incremented every few hundred milliseconds. This gives the impression that the string is being typed out. The pseudocode would more or less look like:

var message = "This is some dialogue.";
var substringLength = 0;

if (someTimeHasPassed)
{
   render(message.substring(0, substringLength);
   substringLength++;
}

This works great, but I'm using a garbage-collected language with immutable strings. Every few milliseconds, I create a new substring on the heap. Garbage collections become very frequent and I receive memory warnings on mobile devices.

Is there a way to generate this typing effect without creating lots of strings in memory?


texts: Adding components to a GameObject referenced within code

texts:
So in my project, I have a class called ComponentRegistry. The idea of this class is to store a dictionary of components and their names. For example:

    public Dictionary<string, MonoBehaviour> registry;
    public MonoBehaviour testComponent;

    void Start(){
        registry = new Dictionary<string, MonoBehaviour> ();
        registry.Add ("TestComponent", testComponent);
    }

    public MonoBehaviour GetScript(string name)
    {
        return registry[name];
    }

Then in a separate class, I will access this dictionary using a string in order to retrieve the associated component, subsequently adding the associated component to the gameObject.

    foreach (string comp in blockInfo.components) {

    //For each of the components that need to be added

        gameObject.AddComponent(ScriptMaster.compReg.GetScript(comp));

        //I know this is incorrect, but the idea is there
}

Just for understanding, compReg is an instance of the ComponentRegister class stored as a static variable within my ScriptMaster class.

But no matter what I try, I have not been able to get this to work. I have switched endlessly between different formatting of adding components to gameObjects, alternating between using Components and MonoBehaviours, adding by type.

Thank you for any insight.


texts: Creating a separate renderer for entities in a 2D game

texts: I'm making a 2D shooter game. As of now, every entity "draws itself", meaning every renderable entity has a draw function. I know it is better if rendering is handled separately, but how can I achieve this? What should I put into the Renderer class?


texts: How can I unpack texture data following a 16 * 8-bit pattern?

texts:
Is possible to unpack texture data following a specific bit packing scheme?

I have read that texture data in HLSL can be read in as 4 floats of 32 bits each totaling 128 bits. The packing scheme I'm looking to use is 16 packing groups of 8 bits each. I am having trouble figuring out how to unpack this data without loss due to it being interpreted as floats.


texts:
I have a very simple 2D game, similar to old-school Mario or Metroid. I'm having a lot of trouble figuring out the proper way to handle player jumping. I've tried several different methods. The first method being that as soon as the player presses the space bar, his position on the Y-Axis is automatically updated so that he is now 50 pixels higher. This didn't work, because his player model immediately jumped up instead of going for that smooth up/down look. The second method I tried was using a Timer. With this, once the player pressed the space bar, his position on the Y-Axis would be incremented every x milliseconds. This also didn't work, for the exact same reason that the first way didn't work. It shot straight up without looking smooth. The last method I tried was a resemblance of my movement on the X-Axis. Instead of waiting for player input, the Y-Axis is constantly being added, but when the player isn't jumping, the yVelocity = 0. When input does come in, an amount is added yVelocity and the player jumps up. I didn't expect this to work, obviously, but it looked better.

So how do you apply jumping correctly? This is something that I've been struggling with for a while, and I just want to get it right. Please don't confuse this question like this question, as they're both different. I need an efficient way to handle jumping so that he looks smooth (as in one motion) going up and down. I can make his falling look good, just not the going up part. Can anybody explain to me how they make jumping look good?

Note: I wrote this question without code because I want a general description of how one might do it. If you do need code or extra details, or anything to understand the question, I'll be happy to add any extra details that you might need.


texts: How can i scale a cube on one side on x only?

texts:
I have in the Hierarchy a empty GameObject and a cube as child of it.
The cube the child is at position 0,0,0 and scale 1,1,1

But when running the game the scaling is on both sides of the cube.
I put the cube as child of the empty gameobject and scaling the empty gameobject but still it's scaling the cube on both sides.

The script is attached to the empty GameObject:

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

public class Walls : MonoBehaviour
{
    Vector3 originalScale;
    Vector3 destinationScale;

    void Start()
    {
        originalScale = transform.localScale;
        destinationScale = new Vector3(100.0f, 0, 0);
    }

    private void Update()
    {
        if (transform.localScale.x != 100.0f)
            transform.localScale += new Vector3(1, 0, 0);
    }
}

This is a working solution:

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

public class Walls : MonoBehaviour
{
    public Transform[] objectstoScale;

    private void Update()
    {
        if (objectstoScale[0].localScale.x != 100.0f)
        {
            objectstoScale[0].localScale += new Vector3(1, 0, 0);
        }
    }
}

But i want to make that the same cube will also scale one side on the z. So the cube will be scaled on both x and z but without filling it one be like frames. So i tried this:

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

public class Walls : MonoBehaviour
{
    public Transform[] objectstoScale;

    private void Update()
    {
        if (objectstoScale[0].localScale.x != 100.0f)
        {
            objectstoScale[0].localScale += new Vector3(1, 0, 0);
            objectstoScale[1].localScale += new Vector3(0, 0, 1);
        }
    }
}

And i have now two cubes childs of the empty gameobject one cube position is 0.5,0,0 the second is 0,0,0.5 but what i'm getting is:

What i want to do is to create automatic a rectangle scaling a cube on 4 sides at the same time not filled rectangle.

For example like this:


texts: How to get scripted programs governing game entities run in parallel with a game loop?

texts:
I recently discovered Crobot which is (briefly) a game where each player codes a virtual robot in a pseudo-C language. Each robot is then put in an arena where it fights against other robots.

A robots' source code has this shape :

/* Beginning file robot.r */
main()
{
    while (1)
    {
        /* Do whatever you want */
        ...
        move();
        ...
        fire();
    }
}
/* End file robot.r */

You can see that :

The code is totally independent from any library/include
Some predefined functions are available (move, fire, etc…)
The program has its own game loop, and consequently is not called every frame

My question is: How to achieve a similar result using scripted languages in collaboration with a C/C++ main program ?

I found a possible approach using Python, multi-threading and shared memory, although I am not sure yet that it is possible this way. TCP/IP seems a bit too complicated for this kind of application.


texts: Driving Force GT: Force Feedback and Wheel Rotation

texts:
I'm diving into the world of game development on PC and have a language agnostic question in regards to controller output.

I have in my possession a Logitech Driving Force GT. This particular steering wheel controller has force feedback (aka vibration or rumble) and the ability to turn the wheel through the game.

What are my options for interfacing with this advanced functionality (not the basic axis rotations and button presses)? I've read the DirectInput and xInput documentation with no luck. Is it like a propriety Logitech only API, or as simple as passing information via HID?

Any pointers that will lead me in the right direction would be greatly appreciated!


texts: How to extract the texture from an image onto a mesh?

texts:
(preamble: I think this fits either here or SO with computer vision tag, I chose gamedev because I think you guys are probably really good with textures and meshes, but tell me if my decision was wrong.)

I want to accomplish the following: Given an image with an object, a 3D mesh very similar to that object, and rendering parameters that render that mesh to the exact location of this object. I want to "extract" the original texture from the image onto the mesh. (So in a later step, I could re-render the mesh from another viewpoint (of course some of the texture would be invisible/black)). My mesh has uv-coordinates for each triangle so I guess I could either "store the texture on the mesh" somehow, or directly backmap it to a 2D texture map.

So I guess what I want to do is kind of texture backmapping/remapping, kind of the inverse of what is done in game-dev when texturing objects. I was having a lot of trouble finding any useful information on Google about what I want to do, so I thought I'd ask here. Maybe I haven't found the right word for it yet. I think there's probably quite a lot of "stuff" involved because pixel in the original image won't exactly correspond to a location on the mesh.


texts: Finding the angle of a line given 2 other lines

texts:
I'm  trying to implement some 2D vehicle physics. For this to work I have 2 wheels attached to the body of the car. After doing some collisions checks I place the wheels at their new position. Say the first wheel is at (-0.5, 1) and the second wheel is at (0.5, 1) I now have to calculate the angle and position of the body between the wheels. In the given example the angle should be 0. But how do I calculate the angle?

Because pictures make everything easier: The blue lines are the positions of the wheels and the pink line is the body. Given the two positions of the wheels, at what angle is the body in relation to the ground?


texts: How do I make my 3d cube move left and right with buttons in Unity with RigidBody.AddForce?

texts:
How do I make my 3d cube move left and right with buttons in Unity with RigidBody.AddForce()?
I can't figure out how to do this in Unity!
I'm trying to make my game playable on Android but I can't get my cube to move with buttons!


texts: Where can I find some good 3D character artists?

texts: I am searching for 3D artists for a 3D iPad game. Is there a good place in the net, where I could find one? He or she should have created game models before.


texts: How to resize a button without resizing its text

texts:
I think it is done with the Anchors of the Rect Transform. I have tried all the possible combinations of the following default anchors:

Unfortunately, when I resize the button in the Scene, the text is always stretched:


texts: Find the closest point along a rectangle, given an another point and direction

texts:
Given a rectangle, and a point with a vector direction towards the rectangle.
How can I find the closest point on the outside of that rectangle to the point in question?


texts: SQl, noSQL, and Doctrine with Symfony 2.0

texts:
I've had the idea of creating a webgame for a while now, and as it becomes more and more accurate i started playing around with Symfony 2.0.

First question :

it seems that it is recommanded to use Doctrine2 (ORM) to manipulate database with Symfony, but i'll feel more comfortable with pure SQL. Am i wrong ?

Second question :

The game i'm thinking of is somewhat a kind of RPG, with the classic character, stats, inventory, etc.

I have some notions of SQL, and i'm improving my knowledge of it at school right now (though i deplore they only teach us oracle environment), but there's a point i need to discuss :
How would you modelise the character's inventory ?
Is a noSQl databse (mongoDB) usefull here ?


texts:
When I do a color exchange directly on the material in playmode, but then I go back to editmode, why do the settings still remain?
For example:
mymaterial.SetColor("_Color", blue);
or
mymaterial.color = blue;


texts: Raycast implementation in order to optimizate collision-detection

texts:
I want to know if a gameobject (a plane) is facing another one to prevent collisions. Right now I have an array that contains all planes in the scene and, for each one, compare position in order to detect if is facing it or not. The number of planes is small, but I want to increase it and this method is a little... Mean.

I was thinking to implement a raycast to detect if the gameobject has another one in front of it. Is it worth? Will it be less expensive? I think that raycast it's very expensive. In addition, I think that I will have to run three raycasts for every plane.

Obviously this is not executed every frame, but every two seconds.


texts:
If I call tex1d from my pixel shader on a texture that has been initialized as a texture2d will it treat the data as a one dimensional array and then just take the element at whichever position you specify?

For instance if you have a 10 x 10 texture(that would be a one dimensional array 100 elements in length) and you call tex1d(mySampler, 0.95) will it give you back element 95?


texts: Spreading server load for a multiplayer game

texts:
My online game is more of a "highly interactive website", as it is played in-browser using webpages and AJAX to communicate with the server, which uses PHP to generate output.

The server is fairly standard, using PHP7, MariaDB, and Memcached (to avoid constantly reloading data from the DB, cache hit rate is about 95%).

All of this works. Fairly well, at that, and it can comfortably handle about 1,000 users actively hammering at the core gameplay element. The problem is that it's not scalable. The only scaling strategy we've had so far is "throw stronger hardware at it", which again works but it's not sustainable.

I want to look into options for spreading the load over multiple servers, but it's daunting.

Most of the game involves manipulating your own characters, and then visiting other player profiles to "interact" with their characters (which awards EXP and bonuses to both parties). There is also trading between players.

Of course if this were just a regular website then I could probably just replicate everything and stick a load-balancer in front of it, but I'm not sure that'll really work here.

I think the most sensible option would be some system of assigning users to a specific server. When you log in a cookie is set to indicate which server you're on, which the load balancer can use to direct your actions to the server your data is on. When visiting another player's profile, the server will request that data from the other player's server. Things like trading will also be handled by having "player one" send a request to their server, which will communicate with "player two"'s server to move data around and complete the action.

Is this realistic? Or am I overthinking it? Are there other options? Ideas?


texts: Introduction to game engines for children

texts:
My friend's 10 years old kid is very interested in programming and video game development. The little guy has already finished CodinGame, so I directed him to other learning games I know of in the meantime. However, I haven't found anything of the sort for game engines

I'm looking for a child friendly introduction to game engines, in the same spirit as CodinGame. It can be about Unity 3D, Unreal Engine or anything of that sort

I've always been interested in teaching Computer Science, and I'd love to be able to use something like that as material


texts: How do I implement space partitioning in entity component system?

texts: My systems work on components without needing to now anything about entities. I want to implement simple grid partitioning, so each entity will be given a cell based on its current position. But how will systems know which components to update and how? For example: CollisionSystem must check collision between each components within a cell, but CollisionComponents must be somehow attached to the grid for system to know what collision to test, which doesn't seem like a good solution. What should I do?


texts:
I'm trying to create a 2D Heads up Display for my players in a 3D OpenTK environment. How I'm doing it is by drawing my 3D elements and then running this code.

GL.MatrixMode(MatrixMode.Projection);
GL.Ortho(-0.5, 0.5, -0.5, 0.5, 1, 100);
GL.LoadIdentity();
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
//Disable all depth stuff
GL.DepthMask(false);
GL.Disable(EnableCap.DepthTest);
GL.Disable(EnableCap.CullFace);
//Pass texture to shaders
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, TextureImg.Handle);
GL.Uniform1(GL.GetUniformLocation(Game.pgmID, "texUnit"), 0.0);
GL.Uniform1(GL.GetUniformLocation(Game.pgmID, "texture"), 1.0);
//Enable vertex attributes
GL.EnableVertexAttribArray(Game.attribute_vpos);
GL.EnableVertexAttribArray(GL.GetAttribLocation(Game.pgmID, "texcoord"));
GL.EnableClientState(ArrayCap.VertexArray);
GL.EnableClientState(ArrayCap.TextureCoordArray);
//MVP matrix is only translation of HUD position
Matrix4 c = Matrix4.CreateTranslation(new Vector3(Position.X, Position.Y, 0)) * Matrix4.CreateScale(0.1f);
GL.UniformMatrix4(Game.uniform_mview, false, ref c);
//Send vertices and uvs to shader
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(verts.Length * Vector2.SizeInBytes), verts, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(Game.attribute_vpos, 2, VertexAttribPointerType.Float, false, 0, 0);

Vector2[] uvs = new Vector2[]
{
    new Vector2(0,0),
    new Vector2(1,0),
    new Vector2(1,1),
    new Vector2(0,1)
};

GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(uvs.Length * Vector2.SizeInBytes), uvs, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(GL.GetAttribLocation(Game.pgmID, "texcoord"), 2, VertexAttribPointerType.Float, false, 0, 0);
//Draw
GL.DrawArrays(PrimitiveType.Quads, 0, 4);
GL.UseProgram(Game.pgmID);
//Make sure I can render 3D again
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GL.DepthMask(true);
GL.Enable(EnableCap.DepthTest);

It works exactly how it's supposed to, except the quad that I draw to the screen is slightly stretched out. It's annoying the absolute heck out of me, and I have no idea what I'm doing wrong.

Edit: Picture


texts: How to rotate sides of rubik's cube by mouse drag?

texts:
I am trying to make a Rubik's cube simulator. I built the Cube by arranging 27 pieces in appropriate place. I wanna simulate the cube like This.
This is what my cube looks like.

I successfully wrote a simple script to rotate the whole cube while dragging the mouse on background. I was also able to rotate sides with key inputs like U, F etc. For this I created 6 empty game objects (UpLayer, FrontLayer etc.) and positioned them in centre of corresponding sides. I store every piece in an array. Now, when the user presses a key, suppose U, I

Make all 9 pieces of upper layer child of empty game object UperLayer at runtime.
Rotate the UperLayer object around its local y axis 90 degrees.
Make required changes in the array.
Un-parent all the pieces.

It works perfectly for every layer. But now, I wanna rotate the layer when user drags it with mouse (Check the above link). I can't think of any approach to do so. I need help.


texts:
Every time I move the hero on my screen I increment a screenOffsetX and a screenOffsetY.
These add 1 if you move right, -1 if left to the sceenOffsetX. Add the screenOffestY +=1 if down, -=1 if up.

I also have a variable for the first time through drawing called drawingForTheFirstTime.

The problem is that I have a level of size 40x40 array. I am drawing a camera view of 20x20. I shift the camera fine as long as I am not near the edges of the map. When I try to go into the upper left of the map, I lose track of the hero.

I dont want the camera to move if the hero is close to the edge of the map. I want him to move independantly of the camera. Otherwise he stays at the same position on the screen while the map moves underneath him. I think it is only my if logic that is broken.

if(!(screenOffsetX != 0 || screenOffestY != 0) && !drawingForTheFirstTime)
{
    return false;
}
else
{
    //move camera
}


texts: Calculating position to position B with speed

texts:
I am trying to find out a formula that calculates the actual position of a player using his speed and a destination position.

These are the informations I have:

Vector3 (X,Y,Z) : Current position
Vector3 (X,Y,Z) : Destination position
float : Speed

I can manage to calculate the angle between these two vectors, but I can't find an efficient formula to calculate the exact position using the speed at each loop. Do you have an idea?

EDIT*

I finally found a formula, but it's not really working as I want...

private void WalkNew()
{
    float speed = 0.1f;
    float distX = this.DestinationPosition.X - this.Position.X;
    float distZ = this.DestinationPosition.Z - this.Position.Z;
    float distance = (float)Math.Sqrt((distX * distX) + (distZ * distZ)); // distance between A and B positions

    float time = distance / speed;
    float currentTime = Time.GetTickFrom(this.lastMoveTime);
    this.lastMoveTime = Time.GetTick();
    float percentage = currentTime / time;

    if (this.Position.IsInCircle(this.DestinationPosition, 0.1f))
    {
        // We arrived
    }
    else
    {
        this.Position.X += distX / percentage;
        this.Position.Z += distZ / percentage;
    }
}

Any thoughts about this formula ?

Thanks


texts:
So, recently I've been learning procedural generation stuff (Perlin noise specifically) and I've kind of hit a wall.

This is the result that I've seen everyone get, but this is what I'm getting,

This is my code, (I'm using python):

import random
import math
import PIL.Image

class Noise:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def lerp(self, start, stop, t):
        return start*(1-t) + (stop*t)

    def smoothstep(self, t):
        return 3*(t**2) - 2*(t**3)

    def gradients(self):
        grads = []
        for _ in range(4):
            x = random.randrange(0, 361)
            y = random.randrange(0, 361)
            grads.append((math.cos(x), math.sin(y)))
        return grads

    def cvectors(self):
        botleft = (self.x, self.y)
        botright = (self.x-1, self.y)
        topleft = (self.x, self.y-1)
        topright = (self.x-1, self.y-1)
        cvecs = [botleft, botright, topleft, topright]
        return cvecs

    def makenoise(self):
        dot = []
        grads = self.gradients()
        cvecs = self.cvectors()
        for i in range(4):
            (x, y) = cvecs[i]
            (a, b) = grads[i]
            dot.append((x*a)+(y*b))
        st = self.lerp(dot[0], dot[1], self.smoothstep(x))
        uv = self.lerp(dot[2], dot[3], self.smoothstep(x))
        stuv = self.lerp(st, uv, self.smoothstep(self.y))
        return stuv

    size = 128
    img = PIL.Image.new('L', (size, size))
    for x in range(size):
        for y in range(size):
            perlin = Noise(random.uniform(0, 1), random.uniform(0, 1))
            img.putpixel(tuple([x, y]), perlin.makenoise())
    img.save("nois.png")

This is just a guess, but I feel like it's a scaling issue. Thanks in advance, and apologies, as well, for the horrible code.


texts: How to program 3D translate widget like in blender?

texts:
Im struggling to achieve the translation widget in my own render engine. Funny enough I thought that widgets are easy, but boy was I wrong...

What I want to implement:

Where I am having problems:

When my object's transform is nested (child) and I want to implement a local translation widget the mouseinput coordinates might become inverted, depending on the current orientation of the object. Example: rotate parent 180° (facing back to camera) and dragging the x axis in left mouse direction results in right motion. Expected: dragging the x axis in right mouse direction results in right motion no matter how the object is rotated.

The motion becomes slow when I approach near perpendicular angles with the selected axis.

My implementation is based on: https://www.codeproject.com/Articles/35139/Interactive-Techniques-in-Three-dimensional-Scenes

I somehow think that I should use something else instead of the virtual planes at initial hitpoint of the raycast.

What's the best approach to implement a translation widget with local coordinates and mouse inputs for drag? I am using pure sharpdx for rendering and bulletsharp for the mouse picking / raytesting.


texts: OpenGL why point's size stay the same while zooming/unzooming

texts:
i'm currently working on a game engine for a college's project. While implementing some debug tools I came across a little problem. When i'm drawing point on the ModelView Matrix the point's thickness doesn't stay at scale with the other objects.

This is how I draw a point

    public static void DrawPoint(Vector3 p1,float size,Color color)
    {
        GL.Disable(EnableCap.Texture2D);
        GL.PointSize(size);
        GL.Begin(BeginMode.Points);
        GL.Color3(color);
        GL.Vertex3(p1.X, p1.Y, p1.Z);
        GL.End();
    });

This is my drawing loop

          protected sealed override void OnRenderFrame(FrameEventArgs e)
    {
        base.OnRenderFrame(e);

        GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
        GL.MatrixMode(MatrixMode.Modelview);
        GL.LoadMatrix(ref _Camera.CameraMatrix);
        GL.PushMatrix();

        RenderGame(); //<-- Where I render world object

        GL.Clear(ClearBufferMask.DepthBufferBit);
        GL.LoadIdentity();
        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        GL.LoadIdentity();
        GL.Ortho(0, Width, 0, Height, -1, 1);
        GL.MatrixMode(MatrixMode.Modelview);

        DrawHUD(); //<-- Where I render UI

        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();
        GL.MatrixMode(MatrixMode.Modelview);

        GL.PopMatrix();
        SwapBuffers();
    }

All points are drawn in the RenderGame method

My question is am I doing something wrong  when I draw points, because it is the only shape that doesn't behave correctly. Or maybe it's just something I don't understand from openGL side.
I'll put images of the problem soon.