texts:
Consider an huge terrain that has a lot polygons, to render this terrain I thought of following techniques:

Using height-map instead of raw meshes: Yes, but I want to create a lot of caves and stuff that simply wont work with height-maps.
Using voxels: Yes, but I think that this would be to much since I don't even want to support changing terrain..
Split into multiple chunks and do some sort of LOD with the mesh: Yes, but how would I do that? Tessellation usually creates more detail not less.
Precompute the same mesh in lower poly version (like Mudbox does) and depending on the distance it renders one of these meshes: Graphic memory is limited and uploading only the chunks won't solve that problem since the traffic would be too high.

IMO the last one sounds really good, but imagine the following process:

Upload and render the chunks depending on the current player position. [No problem]
Player will walk straight forward
Now we maybe have to change on of the low poly chunk with the high poly one
So, Remove the low poly chunk and load the high poly chunk [Already to much traffic here, I think]

I am not very experienced in graphic programming and maybe the upper process is totally okay but somehow I think it is too much.

And how about the disk space it would require.. I think 3 kind of levels would be fine but isn't that also too much?

(I am using OpenGL but I don't think that this is important)


texts: Whats the physics behind the doodle jump game?

texts:
I'd like to know how we can achieve the doodle jump type physics using andengine.

I mean the character is not colliding with the ground blocks when he moves upwards but will collide when he came downwards and will make a jump from their.

Can it be achieved using the collision filter? If yes how? Is it possible to enable and disable collision filter for particular bodies dynamically?


texts:
I've been looking on the internet, but I can't really find any good answers to all my questions..

I started to think about writing a little multiplayer game on my own and after thinking and thinking and thinking about how I should begin I came to the conclusion, that implementing the network communication part at first wouldn't be a bad idea since the testing part becomes "easier".

So my first question is:

Is there any library that would make my life easier if I wanted to write the server part in C++?

I just don't know how one would implement the communication between server and client. Imagine a game that is made up of blocks (like minecraft if you want) but the client should only receive a tiny part of that map. So my question at this one is: Would you send raw byte data? Or would you use more abstract formats like XML? Let us assume that this should work with "many" clients as well..

And here is another thing..

Would one use either a single thread that collects all connections and sends requests to specific worker threads or would you create a new thread for every single connection that is established to the server?


texts:
What I'm doing

In my engine, I'm trying to implement a camera that will follow a target object, such as a player.

I wanted to avoid just simply using the inverse of the target's transformation, because the camera may end up "jerky", so instead I interpolate between the current and target orientation over time, this way the camera's rotation eases in on the desired rotation:

quat targetQuat   = target->getOrientation();
quat currentQuat  = getOrientation();

quat slerpQuat    = glm::slerp(currentQuat, targetQuat, 0.05f);

setOrientation(slerpQuat);

Where my problem begins:

Since I'm just interpolating between quaternions, it is possible that the target may spin faster than the camera can catch up, and may wind up falling behind.

I want to somehow impose a quaternion rotation cap, or somehow determine which of the two is larger so I can min/max 2 quaternions. For example:

quat targetQuat   = target->getOrientation();
quat currentQuat  = getOrientation();

quat slerpQuat    = glm::slerp(currentQuat, targetQuat, 0.05f);
quat maximumQuat  = targetQuat*quat(0.707, 0, -0.3535, 0);

quat desiredQuat  = min(slerpQuat, maximumQuat);

setOrientation(desiredQuat);

How can I determine which of two quaternions rotates/deviates the furthest? Are there any better alternatives methods? The general idea I had was just to min/max the quat such that it always falls within the bounds I need.

I know that I can calculate a delta quaternion, or rather multiply q0 by inverse q1, but even so I don't know what I would do with it or how it could inform me which of the two is the largest one.


texts: User extendable content with Contentmanager

texts:
I developed a towerdefense game that uses xml-Files for almost everything, (creeps, levels, towers, upgrades). Those Xml-files define properties like textures, sounds and values like hitpoints.

My goal is to give the user the power to add and modify those things, which will be some kind of editor in the future probably.
For now it shall be notepad...

So this makes using the ContentManager impossible i guess, since it needs to compile the data into those xnb Files.

I dont have a problem to use XmlSerializer, but how does it work for textures or sounds? Do i need to write my own code for loading the texture into vram etc?

Do i need to reinvent the wheel here and write my own ContentManger or can I make use of an existing feature?

I found a few "similiar" questions but none really gave me an answer.


texts: Orthographic Camera settings for a 2D game

texts:
I'm starting out a 2D wrestling game in Unity 5 and i need some help. The default resolution of game needs to be 320x240. The background sprite that i would be using is 640x480. The camera would move over the background to give it a hovering look. I want the Camera to cover exactly 320x240 resolution. I tried setting the Camera size to 1.2 and it looks approximate but i wanna be sure that the camera is exactly 320x240. By default all the images are set to 100 Pixels per Unit.

So my question is:

How to set the camera to cover exactly 320x240


texts: Why would Rigidbody.AddForce not resulting in movement of my objects?

texts:
I'm trying to get my card objects to spread out randomly but nothing happens. I know the method is called cause I get the prints in the console for each card. But they don't move. No errors reported. The cards have a RigidBody.

public static void CardCascade ()
{
     print ("CARD CASCADE!");
     foreach (var card in Card.Cards) {
          float range = 500F;

          var x = Random.Range (-range, range);
          var y = Random.Range (-range, range);
          card.rigidbody.AddForce (x, y, 0);
          print ("I just added force to card: X/Y " + x + y);
     }
}


texts: Scaling my pixel art platformer from 720p to 1080p

texts:
I'm developing a pixel art 2D platformer for PC and smartphone, but I'm stuck on a technical issue.

I chose to have a 32x32 tile resolution, and a 64x64 character sprite resolution. The levels are divided in to sections that I call "screens", and in each screen I've got 40x22.5 tiles, approximated to 40x23, so the minimum resolution is 1280x720.

In the game, I have got a double-jump mechanic, so I need to have a good vertical view range on each "screen".

Here comes the issue: 1280x720 is not a very high resolution. On HD monitors the window would be not be big, and if I upscale the resolution by 2x, it will be in 2560x1440 and the window would be much larger than an actual HD monitor. If I try sizes in between 1280x720 and 2560x1440 the graphics start to stutter, or are deformed.

How can I solve this issue? Is there a solution that does not require me to redraw all the tiles and the sprites in 16x16 format?


texts: RTS Style Game With Client-Side Prediction

texts:
So, I am currently working on an RTS-like multiplayer game. Units are not controllable by players (they attack-move to a location automatically).

I decided not to go full lockstep but instead do a state-based / prediction hybrid. The game is fully simulated on the client with a state packet for every unit distributed only once per second (Position, health etc.). I've read that this is quite a common method of doing things these days but i'm having major issues with it. One clear problem is with health syncing. Damage is dealt locally on every client machine and corrected via the state packet. This results in issues similar to this:

Projectile hits a unit on a client machine, taking him from 100 health down to 50.
Client only then receives a state packet from the server saying he is on 100 health which spikes it back up.

Of course he will receive another corrective packet later on taking him back down to 50 but this causes really bad visual spikes. This issue gets even worse if you consider the impact of ability damage and such.

Have I completely misunderstood what is required to create a client-predicted game or do I just need to treat every variable on a case-by-case basis? (I.E. Put in silly hacks to make the health not look bad).


texts: How can I adjust the speed my character jumps at?

texts:
I've applied this method How to make a character jump?, like:

  let wallForce = 0;
  const targetVx = -gravity * 4.0;
  const updatePos = delta => {
    const dt = delta * 0.01;

    const oldY = hero.y;

    hero.vy += wallForce * dt;
    hero.vy += gravity * dt;

    hero.x += hero.vx * dt;
    hero.y += hero.vy * dt;

    updateCollisionsBetween(oldY, hero.y);

    hero.vx += (targetVx - hero.vx) * dt;

    wallForce = 0;
  };

and on jump:

  let doubleJump = 0;
  const jump = delta => {
    wallForce = 0;
    hero.vy = -hero.jumpVy;
    if (doubleJump === 1) {
      hero.vx *= 2;
    }
  };

I want to speed up the jumps, that is I want the hero to jump and land faster. If I give a higher negative velocity on the jump (eg. hero.vy = -hero.jumpVy * 2.0), then the hero jumps higher but its speed doesn't change.


texts: Unity move canvas slightly with smartphone acceleration

texts:
I'm developing an AR-App with the Samsung-GearVR. To get a smooth UI, I thought about creating a UI, which is not completely fix, I thought it could be nice, when the UI is slightly behind my head movement, but still lerps to the correct position, when my head is not moving. (A lot of 2D-Sidescroller got this style of camera, which is not fixed on the character, but instead is following the character with a bit of delay, I want this effect for my canvas.)

First off I changed my canvas to World space, which works fine, then I was thinking about the Input.acceleration method, but it does not really give you the actual acceleration, but the actual rotation of the phone. Now I'm struggling, because I don't know, how to get the current acceleration. Is there some better way to achieve this effect or do I have to build something with the Input.acceleration method?


texts: OpenGL Bind all objects at once or single objects at a time

texts:
So if I have a bunch of objects, I do:

glBegin(); renderThing1(); glEnd();
glBegin(); renderThing2(); glEnd();
glBegin(); renderThing3(); glEnd();

Is this more or less efficient than:

glBegin(); renderThing1(); renderThing2(); renderThing3(); glEnd();

Not using unity, using LWJGL and java.


texts: How many BasicEffects do you have in a Game? What is the best way to render multiple objects/shapes at once?

texts:
I'm trying to understand 3D rendering and it seems that everytime you render a new object (A 3D Cube or something) you need to have a new BasicEffect for each Box you render unless you want the exact same texture?

...so if I have over a hundred boxes with each different textures, I need at least as many BasicEffects? Will that not be "too much" for the CPU/GPU in the end or result in lagging? Is there any good way to render multiple objects (cubes or other shapes) at the same time?

I've tried changing the BasicEffect.Texture with each cube drawn, but it resulting in changing the first Cube's texture too.

Any suggestions would be really appreciated, I'm really new to 3D in XNA so I'm trying to wrap my head around the best methods for example render a Map with objects (of shapes).

Example:
I create some Cube3D (by providing location and size) and it creates a list of Vertices.

I have to render it this way:

            gameEffect.TextureEnabled = true;
            gameEffect.Texture = gameTexture;
            gameEffect.EnableDefaultLighting();

            foreach (EffectPass pass in gameEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                foreach (Cube3D cube in gameCubes)
                {
                    cube.Render(GraphicsDevice);
                }
            }

...thereby having the same Texture on each Cube. Are there any other ways?


texts: Single player game into Multiplayer game

texts:
I developed a Single player game in Flash (Tic Tac Toe) and in the Multiplayer mode i will be able to do both player playing on the same system with out network.

I would like to extend it and make it enable to play the Multiplayer game for two player playing it online.

How i can be made give me some ideas , How test the Multiplayer game playing along with different computers(I do not have internet connection in home).

How I able to change the single player game into Multiplayer game , any minor changes required or I have to change the code base completely.

In which way i can make it possible.


texts:
I made a motion blur using OpenGL immediate mode, basically it involves saving screen to texture, then rendering blended texture back (let's skip the details) with something like this:

glBegin(GL_QUADS);
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
        glTexCoord2f(0.0f, 1.0f); glVertex2f(0, 0); // Bottom Left Of The Texture and Quad
        glTexCoord2f(1.0f, 1.0f); glVertex2f(800, 0);   // Bottom Right Of The Texture and Quad
        glTexCoord2f(1.0f, 0.0f); glVertex2f(800,  600);    // Top Right Of The Texture and Quad
        glTexCoord2f(0.0f, 0.0f); glVertex2f(0,  600);
    glEnd();

My problem is: When I use the motion blur, seemly the blended screen get 1 pixel shifted to the opposite of (0, 0), resulting in everything getting blurry, not only the moving stuff.

The stronger I apply the effect, the stronger everything else blurs (as seemly every frame of blur get 1 more pixel shifted).

How I fix that?


texts: Car driving through walls with transform.Translate()

texts:
I need help with a script for a very simple car that uses transform.Translate:

public class car1 : MonoBehaviour {

    public PauseMenu pause;
    [Space]
    public Car_Script car_s;
    public float speed;
    public GameObject car;

    void FixedUpdate()
    {

        if (car_s.InCar == true)
        {
            if(pause.isPaused == false)
            {
                if (Input.GetKey(KeyCode.W))
                {
                    car.transform.Translate(Vector3.forward * Time.deltaTime * speed);

                    if (Input.GetKey(KeyCode.A))
                    {
                        if (speed <= 0)
                        {
                        }
                        else
                        {
                            if (speed > 0F && speed <= 50F)
                            {
                                car.transform.Rotate(Vector3.down, 2F);
                            }
                            else if (speed > 50F && speed < 90F)
                            {
                                car.transform.Rotate(Vector3.down, 1.3F);
                            }
                            else if (speed > 90F)
                            {
                                car.transform.Rotate(Vector3.down, 0.9F);
                            }

                        }
                    }
                    if (Input.GetKey(KeyCode.D))
                    {
                        if (speed <= 0)
                        {
                        }
                        else
                        {
                            if (speed > 0F && speed <= 50F)
                            {
                                car.transform.Rotate(Vector3.up, 2F);
                            }
                            else if (speed > 50F && speed < 90F)
                            {
                                car.transform.Rotate(Vector3.up, 1.3F);
                            }
                            else if (speed > 90F)
                            {
                                car.transform.Rotate(Vector3.up, 0.9F);
                            }

                        }
                    }
                }
            }
        }
    }
}

Whenever I drive the car it immediately goes through walls.

I have colliders on everything. The car has mesh colliders set to convex.

I've searched around quite a bit for answers and it seems that a common one is using rigid bodies. But whenever I even put a rigid body on the car, it flies out into the sky.


texts: Optimize drawing "different" sprites in OpenGL ES 2.0 (batching?)

texts:
I started experimenting with OpenGL ES 2.0, and I'm trying to figure out a way to optimize/batch sprite drawing, where sprites only have the texture in common, but differ in the following properties:

Position
Size
Rotation
Texture coordinates
Color
Hue

I tried two different approaches, which are "good enough" for most games, but I'm still curious on how I could optimize drawing sprites further. All the code is available here on GitHub, but I'll explain my approaches below.

(Both approaches use 4 vertices + 6 indices to draw a quad.)

One drawcall per sprite.

Position and texture coordinates are passed as a vec4 vertex attribute.
The MVP matrix (that handles size and rotation) is passed as a mat4 uniform.
Color is passed as a vec4 uniform and hue is passed as a float uniform.

Since pretty much everything is being passed as an uniform, I have to set all uniforms and call glDrawElements once per sprite.

I can draw 50000 sprites at 60FPS on my desktop (i7 2400k, GTX 970).
One drawcall per N sprites.

The second idea I had and tried was dividing sprites in batches of N. In this approach, everything is passed as a vertex attribute.

 attribute mat4 a_projection_view_model;
 attribute vec4 a_pos_tex_coords;
 attribute vec4 a_color;
 attribute float a_hue;

From my tests it seems slightly faster than the previous approach, but it isn't a big improvement. Also, passing the same mat4 and the same vec4 (a_color) four times seems weird and unnecessarily expensive.

I couldn't figure out a different solution since every sprite has its own MVP matrix, color an hue.

How is sprite batching (when the texture is the same) usually done? Are my approaches "correct" in theory, or am I doing something which is considered bad practice?

How can I optimize my sprite drawing?


texts: How to draw a tileset using HTML5 canvas?

texts:
I have a tileset something like this:

0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16,
17, 18, 19, 20

My tileset draw code looks like this:

var image = new Image();
image.src = '32x32.png';
var tile = 5;
var tileSize = 32;
var x = 100;
var y = 100;
context.drawImage(image, Math.floor(tile * tileSize), 0, tileSize, tileSize, x, y, tileSize, tileSize);

And this code draws the 5 tile, but how would I draw the 10 tile, or the 15 tile without adding tileX and tileY?
I probably need something like if tile is equal to 15, then draw tile 15.


texts: How to automatically scroll vertical text?

texts:
I've a GUI, and a panel with a Text control.

I simply want to do an automatic vertical scroll effect (circular).

Problems I've to solve:
- How to identify if text on my textbox is "too much" and overflow vertical

How to move Text and not textbox transform Y

Can you help me find the correct solution ?

Thanks


texts: A Finite state machine where some states shouldn't be transitioned to even if initial conditions satisfy

texts:
I've built a Finite State Machine for my player. Currently I have only one, locomotion, but I plan on adding more state machines. At the moment state relationship looks something like this:

The blue colored states are ability states. I don't want those states to trigger even if the condition input.JumpActivated is satisfied.
As there's only two such states at the moment, having the condition be abilityManager.isActive(abilityId) && input.JumpActivated instead of just input.JumpActivated is fine, but it seems... manual. As the game grows and more abilities are added, there is bound to be a case where I'll forget to add the condition and then the ability would be active even if it's not supposed to be. I would like to disallow transitioning to those states, but so far none of the solutions I've come up with have looked elegant to me.
This is what I've tried:

Instead of transitions having one condition, they allow multiple conditions, and base state sets a condition that if the next state is of AbilityState type that it must be active.
Implemented state enabling/disabling and had AbilityManager - a component external to the FSM, enable/disable states. Disabled states are not transitioned to.
Implemented state interceptors, which can be subscribed to and if any of them return true the state is not transitioned to

All of those solutions work, but something feels off. I think that all these solutions hide that the states have special logic tied to them in some obscure class/method away from the actual class they belong to.
How do you, experienced game developers, handle such cases?
EDIT: For more context this is a small slice of how my FSM functions now. This is how a typical state might look:
public abstract class OnGroundState : State<IMotor>
{

    protected override void OnInit()
    {
        base.OnInit();
        RegisterTransition(TransitionScope.UPDATE,
            TransitionType.Change(StateId.JUMP),
            ctx => ctx.Entity.Input.IsJumpJustActivated());

        RegisterTransition(TransitionScope.FIXED_UPDATE,
            TransitionType.Change(StateId.IN_AIR),
            MotorConditions.InAirDefaultCondition);
    }

    protected override void OnFixedUpdate()
    {
       // do some logic on fixed update call
    }

}

As you can see, states generally register transitions which are lambdas evaluated immediately (Update) or in fixed timestep (FixedUpdate), and then if the evaluation is true, state is changed to the next state. The problem with this is that while I can define a default predicate such as
ctx => ctx.NextState is AbilityState abilityState && Entity.AbilityManager.IsActive(abilityState.AbilityId)

and then apply it to whatever transition I am checking, like for example
RegisterTransition(TransitionScope.UPDATE,
            TransitionType.Change(StateId.JUMP),
            ctx => ctx.Entity.Input.IsJumpJustActivated() && AbilityCondition(ctx))

this feels prone to errors. I might forget adding the condition to some state transition and then I'll transition to that state even though I don't have that ability unlocked.


texts:
For the past week I've been researching the Marching Cubes algorithm. I hope to use this for Terrain as it would allow the creation of destruction of terrain. After looking at source code and reading many articles I decided to try compiling some of it myself and playing around with it to attempt to make terrain. However, It's giving me a headache and I can't seem to find any good resources on how to do it.

http://i.stack.imgur.com/BbvJR.png

This is from the example found here - http://www.angelfire.com/linux/myp/MC/

The sourcecode relevant can be found on the website.

I added the source code to my project and converted all the code to be used with OpenGL 3.2. However, I don't want to be using this code in my final project. (This is just so I can understand it). I'm having trouble understanding the code. I feel I understand the algorithm now but I can't seem to understand how the object is actually formed.

How can I change this object to create terrain? Are there any better resources on the internet? Thanks in advance.


texts: What is the difference between a video game developer and a video game designer?


texts: How shader program still works even after detaching shader object?

texts:
In the following process of shader creation, shader object is detached after linking program (glLinkProgram), how does the shader program still works after detaching and deleting shader objects?

glCreateShader -> glShaderSource -> glCompileShader -> glCreateProgram -> glAttachShader -> glLinkProgram -> glDetachShader -> glDeleteShader -> Use shader.


texts: what does AngleVectors method in quake 3 source code does

texts:
I just downloaded quake 3 for learning purposes.
I know some of some linear algebra(basic vector math ie: dot,cross product).
However I can't decipher what below method does, I know what is yaw,pitch and roll.
But I can't connect these with vector.
Worse, I'm not sure this fall under what math 'category', so I don't really know how to google.
Hence the question here.
Anyone?

void AngleVectors( const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) {
float       angle;
static float        sr, sp, sy, cr, cp, cy;
// static to help MS compiler fp bugs

angle = angles[YAW] * (M_PI*2 / 360);
sy = sin(angle);
cy = cos(angle);
angle = angles[PITCH] * (M_PI*2 / 360);
sp = sin(angle);
cp = cos(angle);
angle = angles[ROLL] * (M_PI*2 / 360);
sr = sin(angle);
cr = cos(angle);

if (forward)
{
    forward[0] = cp*cy;
    forward[1] = cp*sy;
    forward[2] = -sp;
}
if (right)
{
    right[0] = (-1*sr*sp*cy+-1*cr*-sy);
    right[1] = (-1*sr*sp*sy+-1*cr*cy);
    right[2] = -1*sr*cp;
}
if (up)
{
    up[0] = (cr*sp*cy+-sr*-sy);
    up[1] = (cr*sp*sy+-sr*cy);
    up[2] = cr*cp;
}
}

ddddd


texts: Physics not synchronizing correctly over the network when using Bullet

texts:
I'm trying to implement a client/server physics system using Bullet however I'm having problems getting things to sync up.

I've implemented a custom motion state which reads and writes the transform from my game objects and it works locally but I've tried two different approaches for networked games:

Dynamic objects on the client that are also on the server (eg not random debris and other unimportant stuff) are made kinematic. This works correctly but the objects don't move very smoothly
Objects are dynamic on both but after each message from the server that the object has moved I set the linear and angular velocity to the values from the server and call btRigidBody::proceedToTransform with the transform on the server. I also call btCollisionObject::activate(true); to force the object to update.

My intent with method 2 was to basically do method 1 but hijacking Bullet to do a poor-man's prediction instead of doing my own to smooth out method 1, but this doesn't seem to work (for reasons that are not 100% clear to me even stepping through Bullet) and the objects sometimes end up in different places.

Am I heading in the right direction? Bullet seems to have it's own interpolation code built-in. Can that help me make method 1 work better? Or is my method 2 code not working because I am accidentally stomping that?

EDIT: Another problem with method 1 I just noticed is that the collision response will be way off for collisions against non-synchronized objects. Kinetic bodies kind of shoot stuff to infinity sometimes since they can't be knocked back.


texts: How to set default scale on a per bone basis

texts:
Does anyone know how I can change the default scale on a per bone basis in Maya? (I'm using 2016)

I want the scale to be 1,1,1 for this bone without making it smaller than it currently is.

So, I want to make the default scale of this bone 1.552, 1.552, 1.552.
Therefore, it would read 1,1,1 but still be the same size.

Does anyone know how to do this?


texts: How to create landscape image from 2D map?

texts:
I created a 2D map using Perlin Noise. Based on the value on x,y, I determine an altitude and so a color to apply to my map (8 levels map).

Now, I don't want my player to see the map but I would like him to show him what he sees when he look North direction.

I'll explain the approaches I used to solve my problem and show you the results, then I'll ask my questions for some whom can help.

V1 - the pov approach

I tried a simple approach for the beginning. Based on my character, I start to add what I see in front of me and if I see something higher, i add it on top of the first thing I see + I increase my angle of view.

V2 - the layer approach

For my second approach, I started far from my player position and started to build layers from far to near him. This way I created a vertical cut (from east to west) and put it flat.

V3 - the layer shadowed approach

My third approach is based on the second one + I detected that two elements are one far from the other and I took it in count to generate "shadows" (darker borders).

V4 - the layer shadowed approach + adding pov alteration

Based on V3 approch, hard to explain, the near I am, the less the view is important. (reducing the map view).

Results

I like the way it evolved but I don't like some stuff (for example the cut mountain on first frame)
The second thing I didn't take in count is the altitude of my character.

Do you have any algorithms to solve this problem? I'm not looking for now for optimizations, just to get the best render. I also posted this article on reddit in /r/algorithms


texts: Programming the combat sequence in a role playing game

texts:
I'm trying to write a short "game" where a player goes around and fights monsters but I have no idea how to handle the combat.

For example, say I have a "Warrior" and a "Troll". How do the two fight each other? I know I can do something like

Conan = Warrior.new();
CaveTroll = Troll.new();
Conan.attack(CaveTroll);
CaveTroll.attack(Conan);

But what part of the game controls the monster? Do I just stick the above sequence in a loop until one of them dies? Or does the game "engine" need to have a part that deals specifically with combat? Or is this an aspect of the Troll's artificial intelligence that needs to take care of it's actions?

Also, who/what determines the actions that the monster takes? Maybe a Troll can bash, kick, bite, cast spells, drink potions, use a magical item. Does the game engine determine what action the Troll takes or is that something the Troll class manages?

Sorry I can't be more specific but I need some guidance on which direction to go with this.


texts: Why does launching an object using Rigidbody2d.velocity not work properly

texts:
I am currently trying to launch a gameobject using Rigidbody2d.velocity but whenever I launch it goes backward instead of forwards. I have already tried making the vector 3 that I am using negative, but nothing seems to work. Please help as I don't even know why this happening.

Here is my code

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

public class ArmPower : MonoBehaviour {

    //Priority Script

    public ArmAngle armAngle;
    public bool allowLaunch = false;
    public GameObject armPowerSlider;
    public bool ifLaunched;
    public GameObject armPowerPhone;
    public StartAllowStrengthPower startAllow;
    public PhoneController armPhoneController;

    // Use this for initialization
    void Start () {
        armAngle = FindObjectOfType<ArmAngle>();
        armPowerSlider = GameObject.Find("PowerSlider");
        ifLaunched = false;
        armPowerPhone = GameObject.Find("Phone");
        startAllow = FindObjectOfType<StartAllowStrengthPower>();
        armPhoneController = FindObjectOfType<PhoneController>();
    }

    // Update is called once per frame
    void Update () {
        if (allowLaunch)
        {
            LaunchPhone( (int) (Mathf.Round(armPowerSlider.GetComponent<Slider>().value) ));
            ifLaunched = false;
        }
        if(startAllow.allowLaunchChanger <= 0)
        {
            LaunchPhone((int)(Mathf.Round(armPowerSlider.GetComponent<Slider>().value)));
        }

    }

    public void LaunchPhone(int launchAmount)
    {

        Vector3 launchValue = new Vector3(armPowerPhone.transform.position.x, launchAmount, armPowerPhone.transform.position.z);

        armPowerPhone.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;

        armPowerPhone.GetComponent<Rigidbody2D>().velocity = launchValue;

        armPhoneController.armAudio.Play();

        armPowerPhone.transform.SetParent(null);
        armAngle.allowStrength = false;
        allowLaunch = false;
        ifLaunched = true;
        startAllow.allowLaunchChanger = 5;

    }
}


texts: Unity gizmos vs. referenced game objects

texts:
I'm designing a Unity script that I intend to be highly reusable and as easy as possible to setup within the editor. To this end, a number of properties of this script really need some kind of visual representation on screen.

It is an unresolved question to me whether the design of the script should require references to placeholder game objects, OR just Vector3's and float's that have associated gizmos drawn for them.

Normally a gizmo would be a natural choice, except that Unity gizmos are not directly manipulable (as far as I can tell). Because of this shortcoming I'm having to consider whether depending on references to placeholder game objects is a more designer-friendly approach ultimately, in spite of the extra setup required, and that it might be counter-intuitive when the placeholder game objects disappear at run-time (which my script would do).

Is there a community standard or preference here in this case? Can a Unity-experienced game programmer / designer speak to which approach they feel is more intuitive or more convenient to setup, when using a 3rd party script? Or is this just splitting hairs as long as I ship an example prefab with my script?


texts: Orion Leap Motion`Hand' does not exist in the type `Leap.Leap' - Compile error for core assets

texts:
I was playing with the example scenes provided by the Core Assets pack. Everything was working perfectly in Unity 5.3.2f1 until I opened the PinchingSandbox scene and added two script components to the HandControllerSandbox. I added Hand Cycler and Recording Controls. These scripts were available from the add component drop-down list. Naturally I planned to add my own code, but I first wanted to see if the scene would still run.

Instead of running I suddenly get hundreds of AABB aabb errors which by the look of things is still an unresolved Unity issue. So, I remove the two script components but this doesn't resolve the issue. Perplexed, given that the PinchingSandbox scene worked fine just before I added those two scripts, I waste no time deleting the project and starting afresh.

I imported the unity core assets from the unity asset store like before and now I am very perplexed that I get the following error messages (I have tried reimporting the assets):

I am using Orion, and am not using VR just yet

Related (here for reference)

https://community.leapmotion.com/t/asset-cant-work-correctly-in-unity/1716 - except the assets worked before, so I shouldn't need Unity Pro
https://community.leapmotion.com/t/error-from-new-leap-motion-core-assets-2-2-4/2759 - not exactly the error messages I get, but I have already tried reimporting so remain stumped


texts: Is it legal to pack LibGdx libraries in my jar file? And to obfuscate them?

texts:
I'm using LibGDX and deploying a runnable jar file, using the Eclipse feature, with libraries extracted into it. There are also .so files and .dlls inside.

Is it legal to do so? I didn't find anything about deploying to a single jar file.
If 1 is legal, if I obfuscate the jar file, maybe with ProGuard, will it be still legal?


texts: Baked GI artifacts with Blender and Unity

texts: I've created a very simple model in blender, exported it as FBX and imported in Unity. When I generate light maps on unity I got these strange artifacts (check the images attached here). I've verified the normals and they seems to be correct, the model has been exported with rotation and scale set to 0... any idea where those artifacts are coming from?


texts: How do I write a wave-spawning system for a shoot-em-up?

texts:
I recently played Knightmare Tower and was amazed by the way how different monsters are beign spawned.

I'm aware of time-based and count-based spawing systems in shoot-em-ups. Count-based systems allow a certain number of enemies on screen and spawn more as they die. Time-based ones spawn more at given intervals.

How are these spawning mechanism built? Is there some pattern or theory to it?

Additionally, such games typically have increasingly resilient enemies of increasing numbers of types. How are these balanced?

I'm looking for a general answer, independent of any particular game or technology.


texts: Is it possible to create an "impossible" rooms in games?

texts:
Forgive me my lack of knowlegde, but for quite a long time I asked myself whether it was possible to create a continous game space that some player could walk inside and so on, that would be absolutely impossible in reality, e.g. you have a very small house that allows you to go around it to see all sides and the full dimensions, and then, when you enter, it is like a giant hall, without any loading screen or (internal) "model change" and so on.

I'm no game designer and I never needed to learn 3D-modelling, so I don't know what is possible and what isn't. And is this the same as Is the "impossible object" possible in computer graphics? this? Or is it just the same category, but not exactly the same question?

Thanks.


texts: How to get started being a game designer

texts: I was wondering how can I get started with game design & developement because Im not really good at any programming languages that used to make games


texts:
I'm about to release my second game in the next couple of days. A tester now reported that he has a flicker issue running the game on Linux. It´s related to objects like the water, the hex tiles and object on top of the hextiles.
In Windows everything works like a charm but on Linux all the graphics flicker. I think it´s a graphical problem related to the Z-buffer since the flicking objects all have the same world space position. I´m using the URP and created all the shader by Unity Shader Graph.
Does anyone know how I can fix the issue?
This it how it looks:

Any kind of help is appreciated!
Thanks in advance!


texts: Rotation pitch/yaw reverse problems when picking a tile (2.5D)

texts:
Set-up: 3D world, isometric sprite rendering (4 fixed angles).
This transform matrix is used as camera:

 _transform =
            Matrix.CreateRotationZ(Roll) *
            Matrix.CreateRotationX(Pitch) *
            Matrix.CreateTranslation(new Vector3(-cameraPosition.X , -cameraPosition.Y, -cameraPosition.Z))* //this matrix controls camera position
            Matrix.CreateScale(new Vector3(_zoomScale)) * //scale representing zoom level. This one applies to the textures too
            Matrix.CreateScale(new Vector3(_textureScale)) * //world scale to fit current texture pixel size.
            Matrix.CreateTranslation(new Vector3((_port.screenWidth / 2) - TileOffset, _port.screenHeight / 2, 0)) //offset for having focus in center of screen instead of top left corner + little offset so it will be a tile center
            ;

Roll=-45, Pitch=60. Result:

I've hoped to find a quick picking solution in the inverse matrix:

_inverseTransform =
           Matrix.CreateTranslation(new Vector3(-(_port.screenWidth / 2) + TileOffset, -_port.screenHeight / 2, 0))*
            Matrix.CreateScale(new Vector3(1/_textureScale)) *
            Matrix.CreateScale(new Vector3(1/_zoomScale)) *
            Matrix.CreateTranslation(new Vector3(cameraPosition.X, cameraPosition.Y, cameraPosition.Z))*
            Matrix.CreateRotationX(-Pitch)*
            Matrix.CreateRotationZ(-Roll)
            ;

It doesn't work as expected.
If i remove rotation from matrix build, everything works. The interesting part is if i leave roll component only, everything works too.
I've tried transposed matrices, inverted matrices, rotating on -angle, FromPitchYawRoll matrix (inverted/transposed/-angles). Every time roll works, pitch and yaw aren't.
Pitch only/yaw only can't be inverted too.

It's probably something basic in the matrix math/rotation principles, but i'm failing to grasp it. Any help would be appreciated.

--code removed, not relevant to the case--

Some gifs for better understanding.
Current implementation do this:

If we switch the pitch off, inverse matrix work as intended (white dots mark real tiles grid. Graphical tiles aren't rotated, of course.)

EDIT:
After some matrix calculations i've realised simple thing. Let's point the mouse on the tile (0,2). If i dump all transformations but pitch by several degrees, then tile (0,2) will be drawed somewhere on (0, 1.25).

But if i'll apply inverted (or transposed, or "rotate by -value") matrix to the mouse position (0,2), i'll get same (0, 1.25), which means that the mouse is pointing at (0,1) tile. While it should point at (0, 3). And i don't know how to invert this correctly.

I've also discovered this. But, as you can see in the first answer, knight666 is using scale instead of pitch rotation.


texts: Entity component system design. Should ID of entities be continuous?

texts:
I am implementing an entity-component system. Below is my current implementation in c++.

using ID = std::uint32_t;

class Entity {
public:
    Entity(ID index): index_{index} {
    }

    ID index() const;

private:
    const ID index_;
};

ID Entity::index() const
{
    return index_;
}

class Entity_factory {
public:
    Entity generate();

    void destory(ID id);
private:
    ID count_ = 0;
    std::unordered_set<ID> idle_IDs_;
};

Entity Entity_factory::generate()
{
    if (!idle_IDs_.empty()) {
        const ID id = *idle_IDs_.begin();
        idle_IDs_.erase(idle_IDs_.begin());
        return Entity {id};
    }

    assert(count_ != std::numeric_limits<ID>::max());
    return Entity {count_++};
}

void Entity_factory::destory(ID id)
{
    assert (id < count_);
    idle_IDs_.insert(id);
}

Note I use a hash table to keep track of all "destroyed" ID so I can use it again. This way, all the entity index will be as continuous as possible, so I can store components in a pool and refer them through index without wasting much memory. Another choice I can think is at component pools create a separated "index" array to keep track of entity and store all entity continuous. Which why do you prefer? Or do you have a better solution to this problem?


texts: In LibGDX, how might I make an object orbit around a position?

texts: I need an object, which would be a circle, made with ShaderRender, to orbit around a specified point. In LibGDX is there a method or something that would allow me to accomplish this? If not, could you please provide a code example?


texts: Should I send the elapsed time to the fixed step update function from my game loop?

texts:
I am making a basic game loop based on this article.  This is the nearly final version:

double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE)
  {
    update();
    lag -= MS_PER_UPDATE;
  }

  render();
}

But I think the update function should have elapsed time passed to it so that the game state is calculate based on that.

So this should be the correct version:

double previous = getCurrentTime();
double lag = 0.0;
while (true)
{
  double current = getCurrentTime();
  double elapsed = current - previous;
  previous = current;
  lag += elapsed;

  processInput();

  while (lag >= MS_PER_UPDATE)
  {
    update(elapsed);   ---------------->>>??
    lag -= MS_PER_UPDATE;
  }

  render();
}

Am I right? Because I think a physics engine should always have a delta time to calculate state changes.


texts: How to blur entire scene but a specific spot in Unity?

texts:
What I want is basically: A way to blur every object/sprite on the scene, but have a "blur-free" circular zone, that can move. And everything that's behind that circular zone won't have the blur effect applied to it.

In a 2D mobile game, how would I do that, especially in a way that's not too heavy, performance-wise(if possible).

And if it's not possible to do that in a way that won't completely destroy my performance, I also have those sprites already "pre-blurred" so maybe there's a way to have both blurred and "unblurred" objects at the same position, and only draw the right parts of them as they go through the scene and reach the blur-free zone. If there's a way to do that, that'd also help immensely.

Thanks for your time.


texts:
I'm using c++ and have some problems with the QuadTree design.

I have some components which are not related to the QuadTree directly. These components are eg. RenderableMesh, PointLight, etc. Some of them should be handled by a QuadTree and some of them should not.

I have a "reflection" system, so I can determine the type of a given component, that's not a problem.

A simple restriction is if I want to use a component in a QuadTree, it has to be inherited from the IBoundComponent which can be used to get the bounding box of the object (using a pure virtual function which is implemented in the exact Component)

This seems okay for me but for fast remove/insert operations of "changed components" (eg. the point light's radius is changed) I should store the current node/cell of the QuadTree. And here comes the real problem. Or actually problems.

1)

Because the IBoundComponent does not know about the QuadTree directly, it has to have a public function pair which can be used to set/get the current node. I could use "friend class QuadTree" but that would restrict the spatial implementation to the QuadTree class.

2)

The Node class of the QuadTree is hidden (private). Of course I could store a void* in the IBoundComponent and cast it. Or a base class (eg. ITreeNode) could be used and the QuadTree's Node should inherit from it.

Maybe a cleaner design would be the following:

Don't store anything in the IBoundComponent (expect the bounds...). When a component is changed, I could store the pre-update bounds as well as the post-update bounds. This way I can find which node contains the component and which will contain it. However this is an extra search. So it's a performance loss for cleaner design.

Do you have any good idea? I've searched here but cannot find a good answer for this situation.


texts: How can I smooth my voxels similar to 7 Days to Die?

texts:
7 Days to Die is a voxel space game like Minecraft. However unlike Minecraft, the ground blocks, sand, ore and stone are smoothed so they blend into each other and hills and tunnels appear more rolling and smooth than the blocky Minecraft style.

When you create one of these blocks, you get an octahedron shape object but when you place it, it fills in a smoothed area covering a whole block.

I want to implement something like this in my Unity game. What kind of algorithm can I use to smooth out my blocks, making them blend into each other?

Since I can't start the game right now, I add a screenshot from steamcommunity which shows the block boundaries with the "smoothed" (highlighted) dirt block inside. When the dirt/sand/gravel/ore block falls, it looks the same just not glowing.

The screenshot also shows that the surrounding blocks on that trench wall are forming a slope not a clean edge; They are blended into each other.


texts: How to resize 2D sprites in the size of like 400px to 64px or 32px in a way that doesn't make it look pixelated and weird?


texts:
When I start the script, camera has starting values. When I will move it and click button to set up startign values it is never same. What values I missed?

The best way, I suppose, it is to look at the example: http://jsfiddle.net/VsWb9/6652/

I used console.log for debbuging camera values.

HTML:

<button id="buttonTest">
TEST
</button>
 Please, move cube before click!
<div id="wrapper">

</div>

JS:

var camera, scene, renderer, geometry, material, mesh;

init();
animate();

function init() {
        window.wrapper = document.getElementById('wrapper');
    var buttonTest = document.getElementById('buttonTest');
    buttonTest.addEventListener('click', function() {
        test();
    });

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 500;
    scene.add(camera);

    geometry = new THREE.CubeGeometry(200, 200, 200);
    material = new THREE.MeshNormalMaterial();

    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    renderer = new THREE.WebGLRenderer({
        preserveDrawingBuffer: true
    });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(new THREE.Color("hsl(193, 50%, 57%)"));

    wrapper.appendChild(renderer.domElement);

        controls = new THREE.TrackballControls(camera, renderer.domElement);
    controls.rotateSpeed = 4.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.1;
    controls.noZoom = false;
    controls.noPan = false;
    controls.staticMoving = true;
    controls.dynamicDampingFactor = 0.3;
    controls.keys = [ 65, 83, 68 ];
    controls.addEventListener( 'change', render );

     console.log('camera_default: '+camera.position.x+', '+camera.position.y+', '+camera.position.z);
    console.log('quaternion_default: '+camera.quaternion.x+', '+
            camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);
}

function animate() {

    requestAnimationFrame(animate);
    controls.update();
    render();

}

function render() {
        camera.lookAt(scene.position);
    renderer.render(scene, camera);
}

function test() {
        // lines below shows actual settings
    console.log('camera_now: '+camera.position.x+', '+camera.position.y+', '+camera.position.z);
    console.log('quaternion_now: '+camera.quaternion.x+', '+
            camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);

    window.setTimeout(function() {
        // this is recovering camera values like
        // it was on the sart of script
        // it is not enought, what I missed?
        camera.position.x = 0;
        camera.position.y = 0;
        camera.position.z = 500;
        camera.quaternion.x = 0.0;
            camera.quaternion.y = 0.0;
            camera.quaternion.z = 0.0;
            camera.quaternion.w = 1.0;

        console.log('camera_recover_default: '+camera.position.x+', '+camera.position.y+', '+camera.position.z);
        console.log('quaternion_recover_default: '+camera.quaternion.x+', '+
            camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);
        },1500);
}


texts: How can I prevent movement from analog joystick "bounce"?

texts:
I'm working on a top-down game where the player can move up/down/left/right. The sprite changes to the corresponding direction, and I have an internal value that tracks the direction the player is facing.

The actual movement is handled just by doing rigidbody2D.MovePosition(player.position + movement * speed * Time.deltaTime); and it's working fine. Direction is determined by looking at the absolute values of all 4 axis values and seeing which one is greatest.

The problem I'm having is when using an analog joystick on a controller. So, if you suddenly let go of the stick, it has a little "bounce" where it goes past the center, and into the opposite direction.

I uploaded a slow-motion video of the joystick being released, to show this "bounce."

See GIF here

I added some logging to the input, and here are some numbers:

The joystick bounce always ends up being somewhere between < 0.1 to up to 0.5, for maybe 1 frame in time.

What can I do to mitigate the effects of this bounce? It's causing my player to suddenly look in the opposite direction if they suddenly stop moving.

I've had these ideas for solutions, but I'd love some advice:

Increase deadzone to be over 0.5 - This seems like an easy fix, but that feels like it's too big of a deadzone.
Ignore input if the difference between last frame and current frame is greater than a specific value (maybe 0.5?)
Average out input over the last few frames and then move? Seems like it could be buggy though (and feel laggy)


texts: Ship Controls modeling Real life Physics

texts:
I am working on a 2D ship that will fly around in space (for now, no friction or gravity). The controls are similar to the game Asteroids. My problem is that I am having trouble connecting some variables to real life applications.

For example, if I'm defining the ships velocity, which in real physics is V=distance traveled (or change in position)/time. Should velocity be a Vector2 or just a float (or int). It's how far an object moves so I would think it to be just a single integer or number but then again, your moving on an X and Y axis so shouldn't there be two velocities? One for the X and another for the Y? The velocity being a vector2 actually works really well but when I'm doing other formulas, which are floats or ints, that require velocity I run into issues because I don't have a single number then.

Another issue i'm having trouble grasping is the direction. My code for the direction is:

shipVariables.shipDirection = new Vector2((float)Math.Sin(shipVariables.shipRotation), -(float)Math.Cos(shipVariables.shipRotation));

Which works but it will immediately turns the ship if you rotate the object while moving "forward". My most successful approach to this method was doing this:

shipVariables.shipDirection += new Vector2((float)Math.Sin(shipVariables.shipRotation), -(float)Math.Cos(shipVariables.shipRotation));

The effect I like is that instead of just turning, it essentially has to overcome the previous direction to move to the next. The part I don't like is that it gains speed way to much and it's supposed to just be a direction, not a direction and magnitude.

If I have the velocity and I can get the direction, I will be able to calculate everything else with other formulas that I know (momentum, acceleration, etc...).

Any tips to lead me in the right directions would be great, thanks.


texts: How do I rotate a bounding box together with a sprite?

texts: I have a game object with a sprite that can rotate. It's a rectangle. I need its bounding box to rotate with it. How do I make sure that they can both rotate, but they're always both at the same angle?


texts: Unity3D C# Drag object smoothly on it's x axis that's already bouncing

texts:
In my scene, I have a bouncing ball that collides with a cube. On each collision the ball returns to the same height. How can I get the ball to smoothly move along the x-axis by dragging my finger across the screen, while at the same time having no effect on the y or z values?

The y position is changing every frame depending on the state of the jump, so setting it's y position to transform.position.y in the Update function causes the movement to be jittery if the frame renders when it isn't caught up with the position of the ball.

Also, I set the interpolate value of the rigidbody to interpolate to get a smoother jumping motion, not sure if this is relevant to my problem or not.

Here is where I am at so far with little success. A few mobile games that replicate what I'm trying to achieve in terms of ball movement are Hop, Color Hop, and Splashy!

void Update()
{
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        // Control sliding using touch input.
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        transform.Translate(touchDeltaPosition.x * slidingSpeed, 0, 0);
    }
    transform.position = new Vector3 (Mathf.Clamp(transform.position.x, - xPosLimit, xPosLimit), transform.position.y, transform.position.z);
}


texts: Creating a click and drag system in GameMaker Studio 2

texts:
I am attempting to create a click and drag system in GameMaker 2, for example a dress-up game or maybe a puzzle. How would I go about getting the objects to click and drag?

I'm trying to get it so I can click and drag a piece of clothing, for example, and drag it onto a character and then drag another piece of clothing on as well.


texts:
I am currently making a procedural generated map and wanted to add regions to the cities indicating their reach, the way I am achieving it currently is by expanding outwards from the city center until either the reach of the city is exceeded or water/mountain terrain is met, a bit like raytracing I assume:

This gives the issues seen above, making big ugly/unnatural holes and not filling areas out of "sight" but arguably within the city's reach. City regions are supposed to be blocked by mountains ranges and larger bodies of water, but should curve around small lakes/rocks in a natural way. I can provide my current code put I believe it's fundamentally flawed for what I want to do, and is not usable.

Basically the desired region I want to great should look something like this:

I am at a bit of a loss what to search for to find literature about this topic, whether it be something like an algorithm or hints of some sort, so basically I am asking what this is called. (Any tips/tricks would also be greatly appreciated)


texts:
This is the way I render the score in my main game , and I made this new project to understand how to use it... It works , the score is updated and it display on the screen but the problem is memory... it increase forever , from 20mb when I start untill it runs out of memory..it nevers stop. And in the main game it's working at 2fps... I hate TTF I just can't understand how it works and how should I do it... every tutorial is in c++ and I have to make the game in pure C for college...Help.

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>

int main(int argc, char ** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    SDL_Window * window = SDL_CreateWindow("Example",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
    SDL_Surface * surface;
    SDL_Texture * texture;

    int score = 0;
    char buffer[50];
    int texW = 0;
    int texH = 0;
    TTF_Font * font = TTF_OpenFont("font3.ttf", 25);
    SDL_Color color = { 255, 255, 255 };

    while (!quit)

    {
        SDL_RenderClear(renderer);

        SDL_WaitEvent(&event);
        switch (event.type)
        {
        case SDL_QUIT:
            quit = true;
            break;
        }

        score += 100;
        sprintf(buffer, "SCORE: %d", score);

        surface = TTF_RenderText_Solid(font, buffer, color);
        texture = SDL_CreateTextureFromSurface(renderer, surface);
        SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);

        SDL_FreeSurface(surface);
        SDL_Rect dstrect = { 0, 0, texW,texH };
        SDL_RenderCopy(renderer, texture, NULL, &dstrect);

        SDL_RenderPresent(renderer);
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_DestroyTexture(texture);
    TTF_CloseFont(font);

    TTF_Quit();
    SDL_Quit();

    return 0;
}


texts: Unity: How to receive input events on a RectTransform that does not contain any image/text/...?

texts:
In Unity 2018.3: Imagine a GameObject with only a RectTransform component and a custom script attached to it - otherwise completely empty. Is there a way to receive input events (like IPointerClickHandler.OnPointerClick) without adding any graphical GUI components like text/image/rawimage/etc. ?

In other words: Is there a component or superclass available to receive input events without adding an unused graphical component?

Any clarifications are welcome,
Thank you.


texts:
I am reading an iphone game dev book and I have a question about velocity.

mainly it is this line

playerVelocity = ccp(playerVelocity.x * dec + acceleration.x * sens, 0);

Why do you mutiple the playerVelocity.x by the deceleration. the book says it works by reducing the current velocity so it is easier to change direction and then add the ( acceleration.x * sens. )

this piece of code is using the accelerometer.

float dec = 0.4f; //lower = quicker to change direction;
float sens = 6.0f; //higher more sensitive;
float maxVel = 100;

playerVelocity = ccp(playerVelocity.x * dec + acceleration.x * sens, 0);
NSLog(@"%@", NSStringFromCGPoint(playerVelocity));

if(playerVelocity.x > maxVel)
{
    playerVelocity.x = maxVel;
}
else if(playerVelocity.x < - maxVel)
{
    playerVelocity.x = - maxVel;
}


texts: How can I add up the Transform/GameObjects in the Array of Waypoints in Unity?

texts:
I come up with this code and I try to get the waypoint + 1 when I reach the waypoint and it adds up till the last waypoint. I get Array is out of Index error. I guess I need and foreach loop of waypoints ?

Code:

public float speed;
public float turnSpeed;

public Transform[] waypoints;
private int currentWp = 0;

void FixedUpdate ()
{

    if(waypoints.Length >= currentWp)
    {
        return;
    }

    player.position = Vector3.MoveTowards(player.position, waypoints[currentWp].transform.position, speed * Time.deltaTime);

    var rotation = Quaternion.LookRotation(waypoints[currentWp].transform.position - player.position);
    player.rotation = Quaternion.Slerp (player.rotation, rotation, turnSpeed * Time.deltaTime);

    float distance = Vector3.Distance(player.position, waypoints[currentWp].position);

    if(distance <= 10)
    {
        currentWp++;
    }
}


texts: How can I compute the average color of a texture?

texts:
I'm making a mini-map system for my tile based game, and I thought the best way to accomplish this would be the following:

At the beginning of the game, I calculate the predominant color of every block (tile type), and store it somewhere. Then, to create the mini-map, I just run through the block matrix and paint a single pixel for each block, instead of it's full 16x16 image.

To do this, I need to be able to get the pixel color of a given position in the texture (to compute the average color). The way I was doing it was using getTextureData().

This method, however, seems to be buggy and very poorly-documented. It returns a single array with all the data in what I thought was RGBA order. Thus, the code to get the average color of a rectangle starting at x and y with dimensions w and h from the texture t would be:

int r = 0, g = 0, b = 0;
byte[] bytes = t.getTextureData();
for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
        r += bytes[4*((y + i)*t.getImageWidth() + x + j)];
        g += bytes[4*((y + i)*t.getImageWidth() + x + j) + 1];
        b += bytes[4*((y + i)*t.getImageWidth() + x + j) + 2];
    }
}

r /= bytes.length / 4;
g /= bytes.length / 4;
b /= bytes.length / 4;

However, this does not seem to work. It produces incorrect (often negative) values for each pixel. Is my approach correct or should be I handling the problem differently?


texts: What is a reasonable OpenGL version baseline for a mid-range 3D game?

texts:
I decided recently write a 3D game in my spare time, as I was tired of my daily  "corporate programming". If I expect to be done in 6 months/1 year, which version of OpenGL should I use as baseline? In other words, which version of OpenGL should I require my potential users to have?

I did some OpenGL has a student, but that was in the days of the first edition of the red book. Things have changed a lot since then.


texts:
I'm just starting with threejs, and I'm building a basic first person shooter. I use pointer lock controls.

When the user clicks ("shoots") an object, I remove it and place it at another random position in the 3D world.

When creating the object, I want to position the object randomly, but always inside the current field of view of the user. So the object must be visible in the current view of the user when it's created.

I've tried things like h = tan(fov/2)*dist trying to get the height, but the problem is I don't have the distance between the object and the camera, since the object still needs to be created...

Any help would be much appreciated. I've found similar questions online, but they're usually about changing the camera view based on an object, but that's not what I want since the camera view is determined by the mouse of the user.


texts: What do you call the sounds that play when players place/destroy blocks?

texts:
I'm working on a game and trying to find sounds for it. I'm not sure what terminology to use when searching to find the kinds of sounds I need.

Specifically I'm looking for sounds that make sense for when a player places or destroys a block in my game. What are these sort of incidental environment background effects called in general, so I can better refine my searches?


texts: How to mute the background music when an ad begins to play when a scene is loaded?

texts:
I am a bit of a novice here but I have created a game and I am showing ads when a scene is loaded but the background music keeps playing in the background. Is there a way in which the background music can be paused when the ad begins but resumes playing once the ad has finished?
I have an ad controller for the ad placements and an coroutine to play the ads once a specific scene has been loaded.
The background music is currently working using the inspector on a random background gameobject.
This is my code for the ad manager for the scene:
public static Ads instance;
private string playStoreID = "XXXXXXXX";

private string vidad = "XXXXXX";
private string rewardedVideoAD = "YYYYYYY";
private string BannerAD = "ZZZZZZ";

   private void Awake()
{
    if (instance != null)
    {

        Destroy(gameObject);
    }

    else
    {
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
}

void Start()
{
    Monetization.Initialize(playStoreID, true);
}

public void ShowInterstitialAD()
{

   if (Monetization.IsReady(vidad))
    {
        ShowAdPlacementContent ad = null;
        ad = Monetization.GetPlacementContent(vidad) as ShowAdPlacementContent;

        if (ad != null)
        {
            ToggleMute();

            ad.Show(ToggleMute);
        }
    }

}

void ToggleMute(ShowResult finishState = default(ShowResult))
{
    audioToMute.mute = !audioToMute.mute;
}

public void ShowRewardVideoAD2()
{

    if (Monetization.IsReady(rewardedVideoAD))
    {
        ShowAdPlacementContent ad = null;
        ad = Monetization.GetPlacementContent(rewardedVideoAD) as ShowAdPlacementContent;

        if (ad != null)
        {
            ToggleMute();

            ad.Show(ToggleMute);
        }
    }

}

public void ShowRewardVideoAD()
{

    if (Monetization.IsReady(rewardedVideoAD))
    {
        ShowAdPlacementContent ad = null;
        ad = Monetization.GetPlacementContent(rewardedVideoAD) as ShowAdPlacementContent;

        if (ad != null)
        {

            ToggleMute();

            ad.Show(ToggleMute);
        }
    }

}

}

Here is a picture of the inspector...


texts:
I'm writing code in XNA 4.0, and part of my game entails drawing a textured grid of cubes. It is working, but the problem is the memory usage is growing way too rapidly. Each cube has 8 points, and each point is a VertexPositionTexture. A 16x9 grid takes 50MB memory, and that is just the grid and lines, no textures or anything else. Doubling the grid to 32x18 makes the memory jump to 150MB....I don't understand what is taking up so much room. I draw the grid using DrawUserIndexedPrimitives. The cubes can move around and be different sizes so I can't consolidate them to one set of vertices. What is the proper way to render a few thousand vertices without using so much memory?

These are all the members for my Cube class so far:

GraphicsDevice graphicsDevice; // for drawing this cube
Tileset tileset; // reference to parent object
VertexPositionTexture[] pointList; // the list of 8 vertices
BasicEffect basicEffect; // effect to draw using a shader
Vector3 localTranslation; // just 3 floats
VertexBuffer vertexBuffer; // for sending the vertices to the GPU

There are also a few functions that allocate memory for the pointList...but nothing out of the ordinary...


texts: How can I make a spline out of three points that define a circular arc?

texts:
I was looking at the descriptions of various curve techniques here and noticed the mention of circular arcs. I want to implement something like this, but I'm not quite sure what the correct formula to use is. I can easily find formulas for Bezier or Hermite curves, but when I search for circular arc splines or circular arc interpolation I get a lot of ultra technical articles that are far beyond what I need. My hunch is that I take the angle formed between the endpoints and the control point and use that radius, but I'm still a little too wobbly conceptually to be able to guess a formula.

For those who cannot follow the link, the circle data is given by a starting point and end point which lie on the circle as well as a control point which is used to control the angle.

What formula can I use to interpolate over and approximate an arc of a circle given these three points?


texts:
I'm going to be creating a game soon, and part of it involves spinning sprites. The sprites will be spinning around the Y-Axis (imagine a spinning plate on top of a stick, where the stick stands up vertically.

The main way I've thought of is to have a series of sprites for various rotation values that I blur between as the 'plate' rotates (the sprite is more complex than a plate, though).

The game will be for iPhone, but I'm open to using any 2D gave development library for it.


texts: Problem getting information about running processes with .GetProcesses() in Unity3D on OS X

texts:
I was going to ask this on Unity Answers, but I keep getting an error when trying to get to the site so thought maybe you guys could help. I've also tried the Unity3d subreddit and didn't manage to solve this there either.

I am attempting to get a list of all running processes on my Mac from my Unity application. The final idea is to check if certain applications are running (eg, TextEdit).

I first tried checking for an open application with GetProcessByName, but got this exception even though the process is running:

InvalidOperationException: Process has exited, so the requested information is not available.

Then I decided to go as simple as possible. I figured I'd just print out a list of all running processes to start off with. Here's my code:

    Process[] processes = Process.GetProcesses();
    GUI.Label( new Rect(x, y, 100, 20), "Process: " + processes.Length );
    y += 20;
    foreach (Process process in processes) {
        try
        {
            if (!process.HasExited)
            {
                GUI.Label( new Rect(x, y, 100, 20), "process: " + process.ProcessName );
                y += 20;
            }
        }
        catch (System.InvalidOperationException)
        {
            UnityEngine.Debug.Log("Holy batman we've got an exception!");
        }
    }

When I run this through the editor, here's what I see:

The number of running processes tends to fluctuate around the 200s, but the only process name being printed on screen is Unity.

If I try to print all processes by removing the HasExited if statement I get this (of course they don't all fit on the screen):

Which makes me think that it thinks every process except for Unity has exited...but I have quite a few unterminated processes running, so I wonder why it's not listing those? Basically I need to search through all currently running processes. Any ideas? Is there some sort of permission issue with not being able to access properties of external non-Unity processes?

EDIT: I should note that I've tried this both while running through the editor and after building. When run after building with !process.HasExited one process is listed with a blank name. I guess that might be the currently running application. The process count hovers around 240.


texts:
I've been working on a small engine for educational purposes. I understand that going production with "raw" model files like .obj is wrong mostly because of parsing and loading time. Thus, I want to create a program which parses these raw files and formats it in a new way, let's say using protobuf.

My questions:

Are there any best practices, or any example lib I can take a look at?
What should I do with attached texture files? Seperate files?
How can I support multiple types of models and/or attributes in the models like materials, uv mapping, etc...


texts: How to place rooms proceduraly (rule based) on in a game word

texts:
I am trying to design the algorithm for my level generation which is a rule driven system. I have created all the rules for the system. I have taken care to insure that all rooms make sense in a grid type setup. for example: these rooms could make this configuration

The logic flow code that I have so far

Door{
    Vector3 position;
    POD orient;     // 5 possible values (up is not an option)
    bool Open;
}

Room{
    String roomRule;
    Vector3 roomPos;
    Vector3 dimensions;
    POD roomOrient;     // 4 possible values
    List doors<Door>;
}

LevelManager{
    float scale = 18f;
    List usedRooms<Room>;
    List openDoors<Door>
    bool Grid[][][];

    Room CreateRoom(String rule, Vector3 position, POD Orient){
        place recieved values
        based on rule fill in other data
    }

    Vector3 getDimenstions(String rule){
        return dimensions of the room
    }

    RotateRoom(POD rotateAmount){
        rotate all items in the room
    }

    MoveRoom(Room toBeMoved, POD orientataion, float distance){
        move the position of the room based on inputs
    }

    GenerateMap(Vector3 size, Vector3 start, Vector3 end){
        Grid = array[size.y][size.x][size.z];
        Room floatingRoom;
        floatingRoom = Room.CreateRoom(S01, start, rand(4));
        usedRooms.Add(floatingRoom);
        for each Door in floatingRoom.doors{
            openDoors.Add(door);
        }

//      fill used grid spaces

        floatingRoom = Room.CreateRoom(S02, end, rand(4);
        usedRooms.Add(floatingRoom);
        for each Door in floatingRoom.doors{
            openDoors.Add(door);
        }

        Vector3 nRoomLocation;
        Door workingDoor;
        string workingRoom;
//      fill used grid spaces

//      pick random door on the openDoors list
        workingDoor = /*randomDoor*/
//      get a random rule
        nRoomLocation = workingDoor.position;
//      then I'm lost
    }
}

I know that I have to make sure for convergence (namely the end is reachable), and to do this until there are no more doors on the openDoors list. right now I am simply trying to get this to work in 2D (there are rules that introduce 3D), but I am working on a presumption that a rigorous algorithm can be trivially extended to 3D.

EDIT: my thought pattern so far is to

take an existing open door
and then pick a random room (restrictions can be put in later)
place that room's center at the doors location
move the room in the direction of the doors orientation half the rooms dimension w/respect to that axis
then test against the 3D array to see if all the grid points are open, or have been used, or if there is even space to put the room (caseEdge)
if caseEdge (which can also occur in between rooms) then put the door on a toBeClosed list, and remove it from the open list (placing a wall or something there).
then to do some kind of test that both the start, and the goal are connected, and reachable from each other (each room has nodes for AI, but I don't want to "have" to pull those out to accomplish this).

but this logic has the problem for say the U, or L shaped rooms in my example, and then I also have a problem conceptually if the room needs to be rotated.


texts: Setting object-specific uniforms in a render queue

texts:
I am currently trying to write a (very simple) queued renderer using OpenGL. My current idea looks like this:

struct RenderCommand {
    GLUint  vao;
    GLUint  texture;
    GLUint  shader;
    GLInt   zOrder;
};

void Renderer::addCommand(const RenderCommand& cmd) { /* add to queue */}

void Renderer::render() {
    /* sort the command queue to try and z-sort, batch textures, etc. */

    for(const auto& cmd: queue_) {
        // Bind shader/vao/texture when necessary, issue draw calls
    }
}

Now my problem is this: for sprites for example, I only have one set of quad vertices on the GPU, and I send the sprite vertex shader the sprite size using a uniform. Same goes for the model transform matrix for literally any object. That's okay when render calls issued when iterating over scene objects, but becomes a problem when everything is queued: since most sprites will use the same shader, how do I set the uniform?

I've had a few ideas for solutions, but none of them feels right:

Add data in RenderCommand for size, model matrix, etc. The big problem with that is flexibility: it supports the engine's default sprite (or 3D model or text) shader, but custom shaders with other uniforms won't work.
Add a custom data pointer to RenderCommand to point to uniform data to send before rendering. This is probably the most flexible option.
Add a UniformCommand type, which only uploads a uniform to the currently bound shader. It'll have to be handled carefully when the queue is sorted, to ensure it stays contiguous with whatever shader and model it corresponds to, but that sounds feasible.


texts: Unpacking Sprite Sheet Into 2D Texture Array

texts:
I am using WebGL 2. A tag for it does not exist but it should.

I have a 10x10 sprite sheet of squares that are 16x16 pixels in size (all in one PNG image).

I'd like to create a 2D texture array out of them, where each 16x16 square gets its own, unique Z/depth value.

let texture = gl.createTexture();
let image = new Image();

image.onload = function() {
    gl.bindTexture(gl.TEXTURE_2D_ARRAY, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

    gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 5, gl.RGBA, 16, 16, NUM_IMAGES);

    // Now what?
    // gl.texSubImage3D doesn't let me copy in a section of the src image
}

image.src = "https://source_url.fake/image.png";

I know that gl.texSubImage3D exists but it only accepts an entire image as a source?

glTexSubImage3D: https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTexSubImage3D.xml


texts: How do I implement GPU-based dynamic geometry LOD in OpenGL?

texts:
I'm trying to implement LOD to boost my game's performance. I found a very nice tutorial.

The basic concept that I think I understand is: Get the distance from the camera to the object, check for the right LOD-level and then render the object with the "right amount of instances".

How do I implement that?  The provided example code is a mystery to me...

Some questions:

Is this a good method to implement LOD?
Can someone please explain me detailed, how I have to implement it, with the queries and so on...
I'm rendering all of my objects with

GL11.glDrawElements(GL11.GL_TRIANGLES, model.getRawModel().getVertexCount(),
                    GL11.GL_UNSIGNED_INT, 0);

The example code uses GL_POINTS. Can I implement it also with GL_TRIANGLES?


texts:
As per suggestion I'm splitting How do I create a closed beta on the App Store? up.

Can I upload the game I'm developing to Steam as a closed beta, so I could generate a couple of keys/tokens for my testers? I'm hoping to only publish the game for the public after I'm happy with the game as it's offered on Steam, as a complete user experience which includes the installation process.

If this is not the usual workflow, how should I do it?


texts: How do I efficiently check if a point is inside a rotated rectangle?

texts:
Part for the sake of optimization, part for learning purposes, I will dare to ask: How can I most efficiently check whether a 2D point P is inside a 2D rotated rectangle XYZW, using C# or C++?

Currently, what I am doing is using a "point in triangle" algorithm found in the book Real Time Collision Detection, and running it twice (for the two triangles that make up the rectangle, say XYZ and XZW):

bool PointInTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P)
{
 // Compute vectors
 Vector2 v0 = C - A;
 Vector2 v1 = B - A;
 Vector2 v2 = P - A;

 // Compute dot products
 float dot00 = Vector2.Dot(v0, v0);
 float dot01 = Vector2.Dot(v0, v1);
 float dot02 = Vector2.Dot(v0, v2);
 float dot11 = Vector2.Dot(v1, v1);
 float dot12 = Vector2.Dot(v1, v2);

 // Compute barycentric coordinates
 float invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
 float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
 float v = (dot00 * dot12 - dot01 * dot02) * invDenom;

 // Check if point is in triangle
 if(u >= 0 && v >= 0 && (u + v) < 1)
    { return true; } else { return false; }
}

bool PointInRectangle(Vector2 X, Vector2 Y, Vector2 Z, Vector2 W, Vector2 P)
{
 if(PointInTriangle(X,Y,Z,P)) return true;
 if(PointInTriangle(X,Z,W,P)) return true;
 return false;
}

However, I have the feeling that there might be a cleaner and faster way. Specifically, to reduce the number of math operations.


texts:
In openGL, let's say I output one single point from the vertex shader with this value

gl_Position = vec4(2.0,3.0,5.0,7.0);

what exact math operations happen to "z" after leaving the vertex shader?
what will be the end value of that depth texel?


texts: Random monsters move in-sync instead of individually

texts:
I am making a game in which monsters spawn randomly and begin to move around randomly. I am fairly new at programming but not at game development. Through using a few tutorials I was able to make 1 creature spawn randomly and move randomly (with animations!) in a way that seemed organic instead of robotic.

So, I moved on to the next step of doing this to several creatures. However, when I executed this, I found that instead of executing their own instructions, the rest of the monsters simply mimic the relative movements of 1 central guy. Everyone moves in sync like some North Korean military parade!

I am using foreach loops and random numbers to choose their directions. Since my game is a top down 2d isometric, I am using a dictionary to store 4 directions. I have made some changes based on the suggestions here, and now all the creatures animate! But they still don't change directions or do things on their own.

How do I make them each have their own unique set of instructions instead of everyone just following the dear leader?

Below is a walkthrough of my code:

Monster Initialization:

public void AddCreatures()
{
     NewMonster = new Monster(Texture);
     NewMonster.AddAnimation("northeast", 0, 96, 48, 48, 8, 0.2f);
     NewMonster.AddAnimation("northwest", 0, 144, 48, 48, 8, 0.2f);
     NewMonster.AddAnimation("southeast", 0, 240, 48, 48, 8, 0.2f);
     NewMonster.AddAnimation("southwest", 0, 288, 48, 48, 8, 0.2f);
     NewMonster.AddAnimation("hoon", 144, 336, 48, 48, 1, 1.0f);
     NewMonster.Position = RandomPos();
     NewMonster.DrawOffset = new Vector2(49, 80);
     NewMonster.CurrentAnimation = "southwest";
     NewMonster.IsAnimating = false;
     creatures.Add(NewMonster);
}

Spawn:

for (int v = 0; v < 12; v++)
{
    AddCreatures();
}

Randomize spawn Position:

 private Vector2 RandomPos()
        {
            Vector2 location = Vector2.Zero;
            location.X = rng.Next(300,900);
            location.Y = rng.Next(200, 700);
            return location;
        }

Movements:

 public void Update(GameTime gameTime)
    {
        timenow += (float)gameTime.ElapsedGameTime.TotalSeconds;
        foreach (Monster mon in creatures)
        {
            if (mon.IsAnimating)
            {

                if (timenow - (float)gameTime.ElapsedGameTime.TotalSeconds > 0.5f)
                {
                    mon.Velocity = directions[rng.Next(1, 5)];
                    ChooseAnim(mon);
                    mon.Velocity.Normalize();
                    speed = (float)(rng.Next(0, 3));
                    diff = new Vector2(mon.Position.X - mon.GetLastPosition.X, mon.Position.Y - mon.GetLastPosition.Y);
                    if (Math.Abs(diff.X) >= 4 && Math.Abs(diff.Y) >= 4)
                    {
                        mon.Velocity = directions[rng.Next(1, 5)];
                        ChooseAnim(mon);
                        mon.Velocity.Normalize();
                    }
                    mon.Velocity.X *= speed;
                    mon.Velocity.Y *= speed;

                    timenow = 0f;
                }
                mon.MoveBy(mon.Velocity);

            }
            DoNotExit();
            mon.Update(gameTime);
        }
    }

Animation choosing method:

    private void ChooseAnim(Monster mon)
    {
        if (mon.Velocity == directions[1])
            mon.CurrentAnimation = "northeast";
        if (mon.Velocity == directions[2])
            mon.CurrentAnimation = "northwest";
        if (mon.Velocity == directions[3])
            mon.CurrentAnimation = "southeast";
        if (mon.Velocity == directions[4])
            mon.CurrentAnimation = "southwest";

    }


texts: Sprite not rotating around its centre after Scaling at its centre

texts:
If I scale a sprite at its centre, then try to rotate it around its centre as well, the rotation does not occur around its centre.

If you need to rotate, for example a scaled ball,the way its working it is set the scale center at the top left (0,0) set the scale that you want, and then set the rotation center to the middle of the scaled sprite, and then apply the rotation modifier.

blaBloBliSprite.setScaleCenter(0, 0);
blaBloBliSprite.setScale(0.667f);
blaBloBliSprite.setPosition(557, CAMERA_HEIGHT / 2 - blaBloBliSprite.getHeightScaled() / 2);
blaBloBliSprite.setRotationCenter(blaBloBliSprite.getWidthScaled() / 2, blaBloBliSprite.getHeightScaled() / 2);

But I want to scale a sprite at its centre as well.

Is there any way of doing it?


texts: Formatting Unity data for communication with a REST API

texts:
I am pretty new to unity but I am not new to programming. I am building a Hololens application in Unity 2017.2 and it communicates with a REST api that I built. I am using Unity as a front end more or less and it manages my state. Coming from the web developement world, I have my server converting my models into JSON and I am sending that as a response. For the most part, it works well but since Unity works on an older version of C#, I am having issues working with the JSON data, mainly if the data type is not a string, int, float, or double. For example, if my model contains a date data type I am having issues converting it back into a c# model or even arrays are proving to be a pain. I don’t want to rely on unity packages too much as most I have tried don’t do what I need but I am open to any good ones if you know of any.

My question is, what is the best way to send data from my API to Unity? Should I send xml or a csv instead? Or even a more C# native approach? (If that makes sense)


texts: Sending Vector3 from Unity to custom C# server

texts:
I'm working on a multiplayer game in which the server is a custom C# server.
What I want to do is to store the position of each player in my database.

In my case I'm sending Vector3 as an object through NetworkStream, the problem is how to access to that object in the server side. As you know there is no Vector3 class out there.

I don't want to get the object sent by the client as a string, manipulate it to get the coordinate. I want directly to access the coordinate of the Vector3 in the server side.


texts: Overlapping surfaces in deferred shader blend through one another

texts:
I've just finished implementing deferred shading into my engine, and noticed that when a large object overlaps another smaller object, it blends through it.

For example, in this scene I have a large plane floor, and on top of it rests 3 rectangle walls. When looking at these walls anywhere from above the floor, one can see that the floor blends through the walls.

Alternatively, here's a small video clip showing what I mean

I've been following a tutorial series on OGLDev, and have followed the guide very closely, with the sole exemption being that I use a component based system.

The general format of my rendering loop is as follows:

Prepare the GBuffer
Render Pass (render to FBO, output properties as textures)
Stencil Pass (render light object for stencil operations)
Light Pass (sample from previous textures for lighting calculations)
Final Pass (draw back to default FBO)

Specifically, during my rendering pass the lights are rendered using geometrical objects, such as a bounding sphere for point lights (the only light currently implemented).

I believe that the issue is with the function

  glBlendFunc(GL_ONE, GL_ONE);

I may have multiple lights in a scene, so I need to be able to blend them all together, however when I do that I seem to also get surfaces blending together. If I disable the blend function, the problem disappears but then only the last light processed will render.

The blend function occurs in the following function:

Lighting Pass:

void DLightPointComponent::LightPass(DCamera *cam, GBuffer *gbuffer)
{
    // Obtain required objects for lighting pass
    PointLight point = getPointLight();
    BaseLight base = point.getBaseLight();
    Attenuation atten = point.getAtten();
    DModelComponent *BSphere = getSphere();
    DSuperShader *shader = getSuperShaderProgram();
    QMatrix4x4 mat = getModelMatrix(), mat2 = BSphere->getModelMatrix();
    DMeshComponent *mesh = BSphere->getMeshComponent();

    // Scale up bounding sphere
    float BSphereScale = CalcPointLightBSphere(point)*5000000000;
    mat2.scale(BSphereScale);

    // Prepare textures for sampling
    gbuffer->BindForLightPass();

    // Upload uniforms to shader
    shader->bind();
    shader->bindCamera(*cam);
    shader->pushMatrix(mat);
    shader->pushMatrix(mat2);
    mesh->setShaderProgram(shader);
    mesh->bindToShader();

    ... (upload the many light uniforms to shader) ...

    // Specific OpenGL operations
    glStencilFunc(GL_NOTEQUAL, 0, 0xFF);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendEquation(GL_FUNC_ADD);
    glBlendFunc(GL_ONE, GL_ONE);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_FRONT);

    // Render the bounding sphere
    mesh->pollWholeMesh();

    //Clean up shader
    glCullFace(GL_BACK);
    glDisable(GL_BLEND);
    shader->popMatrix();
    shader->release();
}

My rendering pass in question:

void oglWidget::RenderPass(QList<DComponent*> *components, DCamera *cam, GBuffer *gbuf)
{
    // Obtain the gbuffer shader, and bind all prerequisites to the shader
    DSuperShader *shader = gbuffer->getSuperShaderProgram();
    gbuf->BindForGeomPass();
    shader->bind();
    shader->bindCamera(*cam);

    // Specific OpenGL functions
    glDisable(GL_BLEND);
    glDepthMask(GL_TRUE);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    // Render geometry into GBuffer
    for (int x = 0, total = components->size(); x < total; ++x)
        components->at(x)->pollLocal(shader);

    // Shader Cleanup
    shader->release();
    shader->popMatrix();
    shader->purgeCamera();
    glDepthMask(GL_FALSE);
}

If any further information is wanted, I'll post it.


texts: How can I load and store data for a large map in Unity

texts:
I'm working on a tower defense game. I have this structure:
int array (public int[,,,] gridArray = new int[2000, 2000, 9, 9];)
that I'm using as a map-bible; by map-bible I mean that the array holds all the cell data that the game uses to build its map form.
What I am specifically asking for is a way to store that data in any file format without needing to massively rework my game.
The first two dimensions of the array store x and y, while the last two dimensions hold cell-specific data. In most cases, this cell-specific data stores building health or ammo. But the vast majority of the 81 cells are empty to accommodate more things down the line. It should be noted that all this data is simply integers that are passed on to game objects, for example: newbuilding.health = gridArray [x,y,0,1];
It should be noted I am a novice level programmer and in way over my head, so detail would be appreciated.


texts: What is the best approach to minimise the lag caused by ping when spawning predictable entities?

texts:
When the client clicks it spawns a unit on the client-side which moves in a predetermined path, it also emits an event to the server which indicates that the client has spawned a unit. Once received the server then spawns a unit and updates it.
Both the client and server's update loop occurs 60 times a second, every 5 iterations the server emits the new state to the client which is then applied.
This works fine for very low ping however when the ping increases the unit that is spawned moves for a while and then snaps back to the position it was spawned (because the server has only just received the event and emitted the new state).
What are the ways I can deal with this?


texts:
I want to check if the position I generated has another object or not.
I do this by using Raycast:

private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics2D.Raycast(pos, pos).collider)
      pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

The code above doesn't work at all. I tested it with if statement and for some reason it cannot check that position.

private void RandomOBS()
{
    Vector3 pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);

    while (Physics2D.Raycast(transform.position, transform.position).collider)
      pos = new Vector3(UnityEngine.Random.Range(-8f, 8f), UnityEngine.Random.Range(-4f, 4f), 0);
}

However when you check the transform.position instead of the pos, it works? How and why? All the game objects have the correct colliders & stuff.


texts: Canvas tile grid, hover effects, single tilesheet, etc

texts:
I'm currently in the process of building both the client and server side of an HTML5, canvas, and WebSocket game.

This is what I have thus far for the client: http://jsfiddle.net/dDmTf/20/

Current obstacles

The hover effect has no idea what to put back after the mouse leaves. Currently it's just drawing a "void" tile, but I can't figure out how to redraw a single tile without redrawing the whole map.
How would I go about storing multiple layers within the map variable? I was considering just using a multi-dimensional array for each layer (similar to what you see as the current array), and just iterating through it, but is that really an efficient way of doing it?
Currently the "borders" encroach on one another. I'm not sure what I'm doing wrong? If you hover over and off of the bordering "tree" tiles, you'll notice how it removes part of the neighboring tiles border. This shouldn't need to happen.
Outside of the map, what would be an elegant way of adding Players to the render scene? I've seen a few places that recommend you use multiple canvas's, would you recommend that since they'll probably be moving much more? In addition to that, how can I confine player movement to the grid, similar to how in the pokemon gameboy games, when you tap the left arrow, you always move one "space" that direction. It's not a halfway type deal.
Camera. What would be a good way about adding a "camera" to the equation, so the viewport can pan around a larger map area?
Obstacles. In the newer version of the map, you'll notice an empty obstacles array. Assuming players get added well, what do you think would be good for adding movement obstacles?

Side note

The tile sheet being used for the jsfiddle display is only for development. I'll be replacing it as things progress in the engine.

If you guys have any pointers for my JavaScript, feel free. As I'm more or less learning advanced usage as I go, I'm sure I'm doing plenty of things wrong.

Note: I will continue to update this post as the engine improves, but updating the jsfiddle link and updating the obstacles list by striking things that have been solved, or adding additions.

Edit

Updated link from http://jsfiddle.net/dDmTf/7/ to http://jsfiddle.net/dDmTf/17/ - this handles the "hover" problem, and it's been striked out.

Edit

Updated link from http://jsfiddle.net/dDmTf/17/ to http://jsfiddle.net/dDmTf/19/ - fixes the out of bounds issue with the tiles

Edit

Updated link from http://jsfiddle.net/dDmTf/19/ to http://jsfiddle.net/dDmTf/20/ - adds multiple layers to the equation


texts: What is the logic behind a 3D Projection 'Camera Perspective'?

texts:
Suppose I had a 3D Cube on a 2D plane (screen). And I wanted to use the keypad to move and rotate it.

Without referring to a 3D Game Engine that could do this for me can you explain me the logic or link me to a tutorial on how to rotate the cube or change the camera view?

I tried to look online for a tutorial but its hard to exactly determine what is happening and its relevance to my scenario.


texts:
In Unity3D there's a way to add force at a position and a way to get the velocity at a position. I'd like to  be able to set the velocity of a rigidbody2d at a local position.

My current solution which is very much WIP and very much wrong is as follows:

            _colliderRigidbody.velocity = _knockbackForce;

            Vector2 dirToCenter = (_colliderRigidbody.position - Position2D).normalized;

            float relativeAngleVel = Vector3.Dot(dirToCenter.normalized, _knockbackForce.normalized);
            bool onRight = Vector3.Cross(dirToCenter, _knockbackForce).z > 0;

            relativeAngleVel = 1.0f - Mathf.Abs(relativeAngleVel);

            relativeAngleVel = onRight ? -relativeAngleVel : relativeAngleVel;

            _colliderRigidbody.angularVelocity = -relativeAngleVel * 50;//lol * 50 because who knows what I'm doing >.<

In regards to the problem I'm trying to solve: I have a 'bullet' which hits a target object, I know the point of impact and the direction the bullet is going so I'd like the velocity at that point of impact to be the same as the bullets.


texts: Why do people put a gif animation into a single bitmap?

texts:
Possible Duplicate:
  2D graphics - why use spritesheets?

Something like this file from here:

I haven't write game with animated gif before.... So I wonder why.
When I unpack some game, I see them in this kind of format as well.

Why they are not divide them into individual bitmap?  When they are using it, do they IMPORT them into individual bitmap? or just use display them using offset?