texts:
I'm creating a game inside of a game called "ROBLOX".  The game gives you some scripting tools to allow me to basically create anything I want.  The world is created up by decently large blocks.  There are few exceptions to this (such as ramps, spheres, tubes, etc.)

I want to create a subtle hint of wind.  It will be affecting the game play a little bit and I want the wind to be predictable.  I first thought of creating a flag, but, a flag isn't very well made in such a game as ROBLOX.

So my question is, what different kinds of way can I imply that there is wind?  What other methods will provide me with a natural representation of wind (I don’t want to put a meter or something, I want them to have to find it/figure it out for themselves).


texts: Shifting the world origin and scaling all points?

texts:
Imagine you have a simulation in very large coordinates, and to render it out you need to scale it down (say, solar system -> fitting inside a few thousand units). This is controlled by a float multiplier that you can increase/decrease at runtime.
Additionally, imagine that you have a point in space that can move around, which acts as a kind of "shifted origin", such that objects near that point will be rendered as if they're near the true origin (0,0,0). In this 'example', that may be the player/camera position.
The idea is to allow that 'scaleFactor' to scale up/down the world around that point, e.g. if this shifted origin point is at (1000, 1000) (it's 3D but assume z=0 for convenience), and there are four objects equidistant around it each 500 units away along one or both axes (i.e. (1500, 1500), (500, 1500), etc), then they should be rendered around the true origin (0,0,0) 500 units away, and should move towards/away from it as that scale factor changes.
I can get the objects around the origin, but the scale increasing/decreasing shows the objects either moving to the shifted world origin (i.e. scaling around (1000, 1000)), or to the inverse (-1000, -1000).
Note: this shifted origin point itself is not in render scale - i.e. it is in the 'simulation scale' so you could decide to do something like "shift and scale the solar system around planet X's position in the simulation".
So we need to:

Translate all positions by this shiftPos ('worldOrigin) to get them around the render origin (0,0,0)
Scale by renderScale so they fit within our renderable scene
Draw and/or profit

I tried, foreach obj:
// basePos is glm::dvec3
// renderScale is a float

const glm::dvec3 shifted = glm::translate(-worldOrigin) * glm::dvec4(basePos, 1.0);
const glm::dvec3 scaled = glm::scale(glm::dvec3(renderScale)) * glm::dvec4(shifted, 1.0);

// draw using 'scaled' as position for obj

Here is the result, where green sphere is (0,0,0), red sphere is this 'worldOrigin' / shiftPos, i.e. (1000, 1000, 0) in the above example, and the white spheres are the objects that 'should' be scaling around green. (Ignore the blue sphere and the text - was a leftover). Shown is what happened when I pushed the scale down such that the translation of each white sphere was very small - they converged on -worldOrigin (inverse of red), and when I started increasing the scale, they moved towards and past the red. I am unsure of how to get them to scale centered around green (expand/retract out/in to it).
Thanks!


texts: Need to separate textures for Unity prefabs

texts:
I'm a beginner at Unity and so I apologise if I'm asking a really stupid/simple question.

I have a number of 3d objects that were exported from a Blender project an then imported into Unity.

I grabbed the texture out of Blender and reapplied it in Unity.

Now I want to apply separate textures to each of the Prefab objects, but when I do, the texture change applies to all the prefabs. Likewise, if I try to duplicate one of the prefabs and apply a different texture, it applies to all of the prefabs.

Can I separate the prefabs so that I can apply individual textures to each?

Do I have to reimport the objects individually?


texts: How to add a constant horizontal force just like gravity?

texts:
I want to add a constant horizontal force, just like gravity to a projectile or a sphere moving in 3d space, which will make the projectile or ball or sphere or whatever be influenced by this force so that it will curl in the direction of the constant horizontal force.
I have this code which will add force to the object on swiping the screen, but it doesnt drift/curl or whatever you may call it:

var anglex : float;
var angley : float;
var elevationAngle : Vector3;

function FixedUpdate () {
    if(Input.touchCount>0 && Input.GetTouch(0).phase == TouchPhase.Ended)
               {
                    var touchdeltaposition: Vector2 = Input.GetTouch(0).deltaPosition;
                    anglex = touchdeltaposition.x * Time.deltaTime *2.0;
                    angley = touchdeltaposition.y * Time.deltaTime *5.0;
                    Debug.Log(angley);
                    elevationAngle = Vector3(anglex,angley,0);
                    rigidbody.velocity = transform.TransformDirection(Vector3(anglex,angley,angley ));
                    var elevation : Vector3 = Quaternion.Euler(elevationAngle) * transform.forward;
                    rigidbody.AddRelativeForce(elevation);
                  }
           }

I feel this is simple, but I'm just not able to turn the crank.


texts: Camera field of view: 3D projections & trigonometry

texts:
Okay, here goes.

I have a camera at (Xc, Yc, Zc.) The Xc and Yc coordinates are latitude/longitude, and the Zc coordinate is an altitude in metres. I have a point at (Xp, Yp, Zp) and a field of view on the camera (Th1, Th2) - where Th1 is horizontal FOV and Th2 is vertical FOV.

Given this information, I'd like to:

test if the point is visible (i.e. in the camera's FOV)
project the point as the camera would see it

I've figured out already that the camera's horizontal view at any given distance is tan(Th1) * distance, but I don't know how to test if the point is visible.

Accuracy is not critical. I would prefer a simple solution over a complicated solution, if it works well enough. The computations will be performed by a small microcontroller, which isn't very fast at things like trig functions.

P.S. this is not homework, I'm doing this for some game development. It will be integrated with the real world, hence the latitude/longitude/altitude. It involves flying real RC planes through virtual hoops (or chasing virtual targets), so I have to project the positions of these hoops on a display.


texts:
I'm trying to write an implementation of Core War for an exercise. I'm stuck with the implementation of the X modifier. This is the definition (all quotes from https://corewar.co.uk/standards/icws94.htm):
 Instruction execution proceeds with the A-value set to both the
 A-number and B-number of the A-instruction (in that order) and the
 B-value set to both the B-number and A-number of the B-instruction
 (in that order).  A write to to core replaces both the B-number and
 the A-number of the instruction pointed to by the B-pointer (in that
 order).

Now the implementation of non-division operations in the spec is:
case X:
          Core[((PC + WPB) % M)].BNumber = (IRB.ANumber op IRA.BNumber) % M;
          Core[((PC + WPB) % M)].ANumber = (IRB.BNumber op IRA.ANumber) % M;
          break;

While for division operations (DIV and MOD) is:
case X:
          if (IRA.ANumber != 0)
             Core[((PC + WPB) % M)].BNumber = IRB.BNumber op IRA.ANumber;
          if (IRA.BNumber != 0)
             Core[((PC + WPB) % M)].ANumber = IRB.ANumber op IRA.BNumber;
          if ((IRA.ANumber == 0) || (IRA.BNumber == 0))
             goto noqueue;
          break;

Given the definition, the division operations seem to be implemented correctly, while the other doesn't seem to follow the spec. I'd expect non-division operations to use this implementation:
case X:
          Core[((PC + WPB) % M)].BNumber = (IRB.BNumber op IRA.ANumber) % M;
          Core[((PC + WPB) % M)].ANumber = (IRB.ANumber op IRA.BNumber) % M;
          break;

Am I missing something?


texts:
I have the following four lines before I create the window.

SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

My shaders are of #version 320 core but I get these errors, the first from the vertex shader and the second from the fragment shader.

  ERROR: 0:1: '' :  version '320' is not supported
  ERROR: 0:1: '' : syntax error: #version
  ERROR: 0:2: '' :  #version required and missing.
  ERROR: 0:4: '0' : syntax error: integers in layouts require GLSL 140 or later

  ERROR: 0:1: '' :  version '320' is not supported
  ERROR: 0:1: '' : syntax error: #version
  ERROR: 0:2: '' :  #version required and missing.

I am on OS X El Capitan but this setup worked before with Java.


texts: How set and count Angle of sprite (turret) object in portrait mode in cocos2d?

texts:
I am new in cocos2d.I follow Raywenderlich tutorial series.
I wish to set turrets in below of the screen in portrait mode.when user touch that location fire bullet and turret fire position at the touch location. how can i do that.
Below is my image of turret position.


texts: How to implement transition between screens

texts:
Last night I showed my game to my friends and they said it was a bit jumpy.

The example he gave was in the pokemon games when a battle starts music plays, the screen flashes then pixels out then the pokemon slide on from the side and the battle menu appears.

In my game you are walking along and the all of a sudden you are staring at the battle menu, I do see his point.

I am using a switch statement for my game loop, 1 is a fields and 2 is battle, in battle I run an if statement, if battle active do battle else display results screen/wait for user input.

I thought about making a state for the transition but them I would need a stater for field -> battle, battle -> field, town -> field and the list goes on an on seeming like lots of repeated code to me but I cant think of a way to pause the state while i play an animation like pokemon

With that sort or architecture how would transition between screens smoothly like my mate suggests?

C++ and directX

Edit: the problem I have is that once the state is changed the update routeen for that state is not called so all the sprites disappear as they are textures and only the background remains so I cannot just play a animation then change state or it will look even worse.


texts: Events to communicate between game objects in a component based system?

texts:
I am planning to try and implement a small simple "game engine" thing, with game objects that have their components and all that. My problem is, how do they communicate with one another?

I understand event based communication is popular, but how does it work practically?
Let's say I make a platformer shooter, and the player needs to know about every platform, enemy, bullet, every frame. How will the events look? I thought the player should just say "hey scene manager, I need to know about the platforms. any chance you give me a pointer to those?" and then the player can just handle it. But generally, the address of the platforms (or any other game object) shouldn't change that much, so I am back to a situation where everyone knows about everyone else... This seems like events are useless in this case.

How are events practically used to communicate between objects? is my example the same as what is actually done in games? if not, then what do games do instead?


texts: Any Code Based Driver Optimizations for Far-Object Rendering?

texts:
Are there any video card driver optimizations available to developers to mitigate considerable framerate drops (%50+) which may be caused by Draw Distance defects in a game?

For example, when using a dependency injection pattern - to inject DirectX or Vulkan dependencies into the game library after the fact. (A game engine that may be reused, inefficient, and locked.)

Which cross-API driver features are there - to optimize framerate issues due to rendering distant objects.  (LoD, etc.)

Example :

In a game zone, when the camera is redirected - there is a significant / sharp drop in framerate (50%+), due to the number / complexity of objects far away.

A good example of this is in Dark Souls 3, the Ringed City, Dredge Heap Bonfire.


texts: Calculate the initial velocity of a 3D trajectory

texts:
I've got a 2D projectile code sample working, but would like to extend it to 3D. How would I calculate the initial velocity of the Z-axis? At the moment, I've got:

initVel.X = (float)Math.Cos(45.0);
initVel.Y = (float)Math.Sin(45.0);

How would I convert this to work in 3D, and add the initial velocity for the Z-axis?

In my example, X is across, Y is up down and Z is going into the screen. I also normalize the vector and multiply it by the speed.


texts: Are there any distinct advantages to the ZBrush proprietary formats?

texts:
I apologize if this is off-topic here, but this is the best match I could find on Stack Exchange and I feel I can get some objective analyses.
So, I'm a long time Blender user and a major FOSS proponent, but it's never because I've had anything against charging for software if it provides a unique service. (For a programmer, that would crazy.) I'm considering purchasing a month or two of ZBrush, as it works very well in compatibility layers these days and could be integrated into my workflow. Additionally, FLOSS hasn't overtaken it in every area quite yet, so I imagine there's some serious dedication from their finite engineering team.
However, there are a few practices of the company that concern me a bit, not because I know that they're abused, but because they're very abusable. The proprietary format is one of them. If I open up a program like Blender, GIMP, Photoshop, and so on, I can usually use a generic image as a map or alpha brush; but ZBrush insists on using its own proprietary and undocumented container.
Is there an advantage that it offers, which an open format would not? Is there something clever about it that I'm not seeing yet? Maybe some kind of lossless compression? Compared to a multilayer format like OpenEXR, is there a function to this format aside from market desperation? I am willing to pay $40 a month for quality software, but only if it isn't for something as mild as arbitrary compatibility issues.
In summary, for a guy who renders headless and runs FFmpeg from the terminal—as nature intended—are there any objective advantages to ZBrush for me? Or is it ultimately more of a beginner thing?


texts: What does the identity matrix really do?

texts:
I understand that multiplying by the identity matrix is like multiplying by 1. Why would you multiply a matrix that will only contain the same result?

Also, I'm experimenting with some OpenGL code and found some very interesting things. Like for example:

When you use setIdentity(), the image rotates slower:

Matrix.setIdentityM(mProjectionMatrix, 0);
Matrix.rotateM(mProjectionMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);

But if you try to remove the setIdentity(), the image will rotate so fast...
first it will rotate clockwise so fast, and then it will become slower until it stops and then it will begin to rotate counter clockwise, and then will stop again, then rotate clockwise.

I really don't understand how the identity matrix affects them despite multiplying by 1.

Can someone explain to me what's going on?

Here is the tutorial I am following.


texts: android zoomable and scrollable board game

texts:
I'm developing a Android board game and have a question regarding creating a board that is zoomable and scrollable. The board contains a static background, characters (players) and  the actual "level" which is drawn using tiles.

My solutions is to have a collection of elements (tiles, figures, all game elements - all have x,y coordinates and width + height), a camera and a renderer that draws the collection according to cameraX,cameraY, cameraWidth and cameraHeight. So if a user would scroll to the right, the camera would just set the cameraX appropriately - and the surface is scrollable. And if a user would zoom in/out the renderer would just scale every element image appropriately.

Example code for the renderer with scrollable surface and zoom in/out

    protected function draw(Canvas c){
      Collection elements = collection.getElements(cameraX,cameraY,cameraWidth,cameraHeight);
      if(elements.size() > 0) {
         for(int i = 0; i < elements.size(); i++) {
              elements.get(i).drawElement(c);
         }
      }
    }
    .
    .
    .
    // element class drawElement function
    protected drawElement function(Canvas c) {
        if(this.image != null) {
          int w = this.width;
          int h = this.height;
          if(this.zoomFactor < 1) {
             w*=this.zoomFactor;
             h*=this.zoomFactor;
          }
          c.drawBitmap(this.image,this.x,this.y,w,h);
        }
    }

Is this the best solutions?
Could it be achived somehow else?
Could scrolling be achived using a ScrollView?

I dont wanna use any engine, because this is for a school project.


texts: Calculating camera frustum planes using existing matrix

texts:
I'm trying to get basic frustum culling against an AABB working, and I'm having a bit of trouble figuring out how to extract the frustum planes from my camera's transform matrix. All the example code I've found expects position, look, and up vectors, as you'd pass to gluLookAt. My camera matrix can be transformed by a parent and other bits of code, so those vectors never exist anywhere that I could use them.

I've looked at code for gluLookAt and tried to graft the inverse of that on top of the Lighthouse3D example for creating the Frustum planes. It's really close to correct, but I have objects flickering in and out of existence still, so something's not quite right. All of the related code is here, so I'm hoping this will be an easy find for somebody.

struct Frustum {
  enum {
    TOP,
    BOTTOM,
    LEFT,
    RIGHT,
    NEAR,
    FAR
  };

  Frustum(hsMatrix44 cam, float znear, float zfar, float angle, float aspect) {
    float nw, nh, fw, fh, tang;
    tang = (float)tan(angle * 0.5);
    nh = znear * tang;
    nw = nh * aspect;
    fh = zfar  * tang;
    fw = fh * angle;

    hsVector3 dir,nc,fc,X,Y,Z,P,U;
    hsVector3 ntl,ntr,nbl,nbr,ftl,ftr,fbl,fbr;

    Z.X = -cam(2,0);
    Z.Y = -cam(2,1);
    Z.Z = -cam(2,2);
    U.X = cam(1,0);
    U.Y = cam(1,1);
    U.Z = cam(1,2);
    X = U.crossP(Z);
    X = X * (1.f/X.magnitude());
    Y = Z.crossP(X);
    hsMatrix44 icam = cam.inverse();
    P.X = icam(0,3);
    P.Y = icam(1,3);
    P.Z = icam(2,3);
    nc = P - Z * znear;
    fc = P - Z * zfar;

    ntl = nc + Y * nh - X * nw;
    ntr = nc + Y * nh + X * nw;
    nbl = nc - Y * nh - X * nw;
    nbr = nc - Y * nh + X * nw;
    ftl = fc + Y * fh - X * fw;
    ftr = fc + Y * fh + X * fw;
    fbl = fc - Y * fh - X * fw;
    fbr = fc - Y * fh + X * fw;

    planes[TOP] = planeFromPoints(ntr, ntl, ftl);
    planes[BOTTOM] = planeFromPoints(nbl, nbr, fbr);
    planes[LEFT] = planeFromPoints(ntl, nbl, fbl);
    planes[RIGHT] = planeFromPoints(nbr, ntr, fbr);
    planes[NEAR] = planeFromPoints(ntl, ntr, nbr);
    planes[FAR] = planeFromPoints(ftr, ftl, fbl);
  }

  bool checkBox(const hsBounds3Ext& box) {
    for(int i = 0; i < 6; ++i) {
      float d0, d1;
      d0 = planes[i].W + planes[i].N.dotP(box.getMins());
      d1 = planes[i].W + planes[i].N.dotP(box.getMaxs());
      if((d0 < 0.f) && (d1 < 0.f))
        return false;
    }
    return true;
  }

  hsPlane3 planes[6];
};

hsPlane3 planeFromPoints(hsVector3 a, hsVector3 b, hsVector3 c) {
  hsPlane3 p;
  hsVector3 tmp0, tmp1;
  tmp0 = a - b;
  tmp1 = c - b;
  p.N = tmp1.crossP(tmp0);
  p.N = p.N * (1.f/p.N.magnitude());
  p.W = -(p.N.dotP(b));
  return p;
}


texts: Spawning player at a certain point after a new scene was loaded

texts:
I have a Game Manager with a DontDestroyOnLoad function on it, before loading a scene I'm passing the variables needed to reset players position to a certain position. This is what my code looks like;

public IEnumerator LoadingNextLevel(int levelToLoad, string spawnPoint)
{
    pState.movingToNextLevel = true;
    fadeToBlack.SetTrigger("FadeOut");

    yield return new WaitForSeconds(0.5f);
    SceneManager.LoadScene(levelToLoad);
    fadeToBlack.SetTrigger("FadeIn");
    pState.movingToNextLevel = false;
    if (spawnPoint == "Red")
    {
        player.transform.position = GameObject.FindGameObjectWithTag("Red").transform.position;
    }
    else if (spawnPoint == "Blue")
    {
        player.transform.position = GameObject.FindGameObjectWithTag("Blue").transform.position;
    }
}

This doesn't give me any error, nor it does the job. What am I doing wrong?


texts: Should the engine for an eventual web-based game start as a web-service?

texts:
I've recently decided to start writing an engine for a card game. I'm not a big "cards" player, but a friend introduced me to the game (it's a spin on the game Danish), and I fell in love.

I want to develop the game in 3 segments:

The basic engine, handles cards/decks/gamestate, etc.
A user interface (in the form of a mobile/desktop web app.)
An artificial intelligence with various strategies/difficulties, etc.

These are very distinct projects, in my mind... and I'm struggling with seeing how they'll all fit together in the long run.
At first, I don't even want to be able to "play" the game using the engine. The engine will primarily be tested by its unit tests. Play testing won't start until a client exists. So there's something of a client-server relationship here.

The engine is a very large piece of the puzzle. What I'd like to know is: how would you go about developing the "public API" for this engine?

I was thinking the engine could be a very basic web service, that returns its state via queries to a RESTful API, but I'm worried that developing the engine itself as a web app may lead to poor programming decisions. (For instance, if I chose an MVC micro-framework, well, this API wouldn't really have views... it's just returning serialized objects via JSON, or something to that effect. Is it bad to use MVC for a service like this? )

My other idea was that the engine would just be a console app, and I would later write a bridge of some kind to pipe data between it and the web-app. (The bridge could really be anything. I mean, the web server and the game engine could both idle in an IRC server and share their state in channels.)

What approach would you take (develop as a web service, or develop as a standalone app and bridge it later), and why?

Thanks,
Robbie.

EDIT: So I guess this belongs in Game Development. To clarify, I'm going to write a card game engine. I'm trying to figure out the best way to expose the engine's API so it can be integrated in the future with a web client, and an AI client.

I didn't even have an account here, so howdy :)


texts: Internationalization (i18n) in Flash games? Is there an easy way?

texts:
I want to internationalize some texts in a flash (not flex) game I'm working on and I can not find an easy way to achieve that... I have found some libraries and other solutions, but I expected something a lot easier (it is really easy with other technologies).

Do you have experience in this? How do you do it?


texts:
So, I'm creating a 2d, top down, sprite based (tiled) game, and right now I'm working on maps (well, a map editor at the moment, but it will be creating my maps, so basically the same thing).
The scenario
So, I'm thinking about efficiency and creating a map in pieces. In each piece, I plan on having 'layers'. Basically, I plan on rendering it down to a 'below hero' level, and an 'above hero' level, with the hero rendered in between obviously. There will likely also be a 'on level with hero' layer, but I'm not quite there yet. Not even worrying about events or interaction yet. Just looking to get a hero on the screen.
Now for movement, I obviously need to know what tiles can be moved and in what direction. My plan at the moment is each tile getting 8 bits (4 'can enter in direction' bits, 4 'can leave in direction'). This will allow me to limit movement and even allow one way directional movement.
The dilemma
This works great for a lot of scenarios. It will allow me to store a map in essentially 3 layers, a string, and gives me flexibility going forward. However, I can't create maps that themselves have layers. A good example is a bridge where the user can go under or over the bridge without invalid moves being allowed. I can't create a platform and allow movement underneath. These are things I would like to be able to include in my game.
My idea
In theory, I could allow multiple hero layers and then allow multiple sets of 'below' and 'above' layers (or sandwich layers). But this complicates my system, and makes movement between maps potentially tricky (If the hero is on the third layer at the edge of a map, but that corresponds to the second layer on the other map, how can I allow or disallow movement).
My question
Is there a better way to manage multiple maps with multiple levels like this where a users level may be 'connected' on different levels on different maps?
Or even...
Am I doing this the hard way? Is there a more standard way to handle top-down 2d tiled maps that I am just not aware of?
Things to note or that might be helpful

This will be done in Javascript (transferred around in JSON)
State will need to be transferred quickly, so a map-id and x/y/direction should be enough to get me a boolean 'can move' value
Maps will not be standard sized (though they will be in a certain number of tiles)
Making an editor tool so that I can have others help, so something that I can create in a tool would be helpful
'Teleportation' locations will likely need to exist to get into building maps and to and from different map sets (which will not necessarily be connected), but have not been created yet (lumping in with events at the moment).


texts:
So I'm making a 2D tile based game but I can't quite get the collisions working properly. I've taken the code from the Platformer Sample and implemented it into my game as seen below.

One problem I'm having is when I'm on the ground for some strange reason I can't move to the left. Now I'm pretty sure this problem is from the HandleCollisions() method because when I stop running it I can smoothly move around with no problems. Another problem  I'm having is when I'm close to a tile the character jitters very strangely.

I will try to post a video if necessary. Here is the HandleCollisions() method:

void HandleCollisions() {
    Rectangle bounds = BoundingRectangle;

    int topTile = (int)Math.Floor((float)bounds.Top / World.PixelTileSize);
    int bottomTile = (int)Math.Ceiling((float)bounds.Bottom / World.PixelTileSize) - 1;
    int leftTile = (int)Math.Floor((float)bounds.Left / World.PixelTileSize);
    int rightTile = (int)Math.Ceiling((float)bounds.Right / World.PixelTileSize) - 1;

    isOnGround = false;

    for(int x = leftTile; x <= rightTile; x++) {
        for(int y = topTile; y <= bottomTile; y++) {
            if(world.Map[y, x].Collidable == true) {
                Rectangle tileBounds =
                     new Rectangle(x * World.PixelTileSize, y * World.PixelTileSize,
                                           World.PixelTileSize, World.PixelTileSize);
                Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds,
                                                                         tileBounds);

                if(depth != Vector2.Zero) {
                    if(Math.Abs(depth.Y) < Math.Abs(depth.X)) {
                        isOnGround = true;
                        position = new Vector2(position.X, position.Y + depth.Y);
                    }
                    else {
                        position = new Vector2(position.X + depth.X, position.Y);
                    }

                    bounds = BoundingRectangle;
                }
            }
        }
    }
    ...
}


texts: How should game objects be aware of each other?

texts:
I find it hard to find a way to organize game objects so that they are polymorphic but at the same time not polymorphic.

Here's an example: assuming that we want all our objects to update() and draw(). In order to do that we need to define a base class GameObject which have those two virtual pure methods and let polymorphism kicks in:

class World {
private:
    std::vector<GameObject*> objects;
public:
    // ...
    update() {
        for (auto& o : objects) o->update();
        for (auto& o : objects) o->draw(window);
    }
};

The update method is supposed to take care of whatever state the specific class object needs to update. The fact is that each objects needs to know about the world around them. For example:

A mine needs to know if someone is colliding with it
A soldier should know if another team's soldier is in proximity
A zombie should know where the closest brain, within a radius, is

For passive interactions (like the first one) I was thinking that the collision detection could delegate what to do in specific cases of collisions to the object itself with a on_collide(GameObject*).

Most of the the other informations (like the other two examples) could just be queried by the game world passed to the update method.
Now the world does not distinguish objects based on their type (it stores all object in a single polymorphic container), so what in fact it will return with an ideal world.entities_in(center, radius) is a container of GameObject*. But of course the soldier does not want to attack other soldiers from his team and a zombie doesn't case about other zombies. So we need to distinguish the behavior. A solution could be the following:

void TeamASoldier::update(const World& world) {
    auto list = world.entities_in(position, eye_sight);
    for (const auto& e : list)
        if (auto enemy = dynamic_cast<TeamBSoldier*>(e))
            // shoot towards enemy
}

void Zombie::update(const World& world) {
    auto list = world.entities_in(position, eye_sight);
    for (const auto& e : list)
        if (auto enemy = dynamic_cast<Human*>(e))
            // go and eat brain
}

but of course the number of dynamic_cast<> per frame could be horribly high, and we all know how slow dynamic_cast can be. The same problem also applies to the on_collide(GameObject*) delegate that we discussed earlier.

So what it the ideal way to organize the code so that objects can be aware of other objects and be able to ignore them or take actions based on their type?


texts: Unity c#: Interface object never equals null

texts:
I've created an interface class for some mechanic I'm using to interact with things in my game. Now, I noticed that checking if that value is null never returns true.
Here's a screenshot of where this happens:

The error I get is the following:

MissingReferenceException: The object of type 'InteractiveItem' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
InteractiveItem.CurrentGameObject () (at Assets/Scripts/Interactive/InteractiveItem.cs:10)
Interactive.ManualStopInteract () (at Assets/Scripts/Interactive/Interactive.cs:30)

The line where this fails is:

if (IsInteracting() && this.interacting.CurrentGameObject().GetComponent<InteractiveUtilityChest>() == null && !MainReferences.UIReferences.IsAnyMenuWindowOpen()) {
        // do something
}

The IsInteracting() check is for some reason returning true here because the last line (InteractiveItem.cs:10) is in the method interacting.CurrentGameObject()

I don't get how this can happen or how I should solve it. As far as I know, an interface is a nullable type.


texts: How do I prevent a KActor from changing the orientation of its Z-Axis?

texts:
So I have an object that inherits from KActor that I would like to behave as a dynamic physics object, but I want its Z-Axis to remain upright, but very stiffly. I've tried the bStayUpright that triggers the "Stay Upright Spring". The problem is, it's a spring, and the object in question oscillates into position when I want it to remain oriented properly without wobbling.

In the image above, the yellow block has fallen onto the gray box, and it is currently pivoting about the contact point as it tries to right itself.

Should I be tweaking the StayUprightMaxTorque and StayUprightTorqueFactor parameters, or should I be using a Constraint of some sort?


texts: Generate levels in real-time with the Procedural CityEngine

texts:
Has anyone used the Procedural CityEngine to generate levels in real-time?

It seems to get used in production or pre-production due to its sizable overhead, but has anyone tweaked it to run in real-time either in a test or in a game?

Edit: Please include the person or group who did this, the game or test it was used in and a brief description of how it was done.


texts: Unity question: When attaching my custom camera script camera shakes when player starts to move fast

texts:
Here is my player code.

Rigidbody rb;

Vector3 currMovement;
public float jumpSpeed = 10;
public float moveSpeed = 10;
public float rotSpeed = 180;

float distToGround;

public float smoothTimePos = 0.25f;
float currPos;
float targetPos;
float posVel;

public float smoothTimeRot = 0.25f;
float currRot;
float targetRot;
float rotVel;

void Start()
{
    rb = GetComponent<Rigidbody>();
    distToGround = GetComponent<Collider>().bounds.extents.y;
}

bool isGrounded() { return Physics.Raycast(transform.position, Vector3.down, distToGround + 0.1f); }

void Update()
{
    targetRot = Input.GetAxisRaw("Horizontal") * rotSpeed * Time.smoothDeltaTime;
    targetPos = Input.GetAxisRaw("Vertical") * moveSpeed;
}

void FixedUpdate()
{
    Move();
}

void Move()
{
    if (isGrounded())
    {
        if (Input.GetButtonDown("Jump"))
            rb.velocity += Vector3.up * jumpSpeed;
    }

    // Rotation smoothing.
    if (targetRot > 360)
        targetRot -= 360;
    if (targetRot < 0)
        targetRot += 360;
    currRot = Mathf.SmoothDampAngle(currRot, targetRot, ref rotVel, smoothTimeRot);

    transform.eulerAngles += new Vector3(0, currRot, 0);

    // Movement smoothing.
    currPos = Mathf.SmoothDamp(currPos, targetPos, ref posVel, smoothTimePos);
    currMovement = new Vector3(0, 0, currPos);
    currMovement = transform.rotation * currMovement;

    rb.position += currMovement * Time.smoothDeltaTime;
}

I have a Rigidbody attached to my player. I think the problem is with my camera script. Here is my camera script.

public Rigidbody player;
Quaternion targetLook;
Vector3 targetMove, targetMoveRaycast, targetMoveUse;
public float smoothLook = 8, smoothMove = 0.25f;
public float distFromPlayer = 5, heightFromPlayer = 3;
Vector3 moveVel;

void LateUpdate()
{
    CameraMove();
}

void CameraMove()
{
    targetMove = player.position + (player.rotation * new Vector3(0, heightFromPlayer, -distFromPlayer));

    RaycastHit hit;
    if (Physics.Raycast(player.position, targetMove - player.position, out hit, Vector3.Distance(player.position, transform.position)))
    {
        targetMoveRaycast = hit.point;
        targetMoveUse = targetMoveRaycast;
    }
    else
    {
        targetMoveUse = targetMove;
    }

    transform.position = Vector3.SmoothDamp(transform.position, targetMoveUse, ref moveVel, smoothMove);

    targetLook = Quaternion.LookRotation(player.position - transform.position);
    transform.rotation = Quaternion.Slerp(transform.rotation, targetLook, smoothLook * Time.smoothDeltaTime);
}

The player is not an parent of my camera. When I parent the player to my camera the shake stops. But I want a custom smooth camera movement with my custom scirpt, so I can't make the player a parent of the camera.


texts: The Pixel Shader unit expects a Sampler configured for default filtering to be set at Slot 0 [...]

texts:
I don't understand this error. The full output being :

  The Pixel Shader unit expects a Sampler configured for default
  filtering to be set at Slot 0, but the sampler bound at this slot is
  configured for comparison filtering.

Here is how I create the sampler state.

// Skybox sampler description
D3D11_SAMPLER_DESC skyboxSamplerDesc;
ZeroMemory(&skyboxSamplerDesc, sizeof(D3D11_SAMPLER_DESC));
skyboxSamplerDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
skyboxSamplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
skyboxSamplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
skyboxSamplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
skyboxSamplerDesc.MipLODBias = 0.0f;
skyboxSamplerDesc.MaxAnisotropy = 16;
skyboxSamplerDesc.ComparisonFunc = D3D11_COMPARISON_EQUAL;
skyboxSamplerDesc.MinLOD = 0;
skyboxSamplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

// Create the skybox texture sampler state
hr = g_d3dDevice->CreateSamplerState(&skyboxSamplerDesc, &g_SkyboxSamplerState);
if (FAILED(hr)) return false;

The bindings.

ID3D11SamplerState* samplerStates[2];
samplerStates[0] = g_SkyboxSamplerState;
samplerStates[1] = g_PixelDepthSamplerState;
g_d3dDeviceContext->PSSetSamplers(0, 2, samplerStates);

HLSL side.

SamplerState sbSamplerState : register (s0) {
    Filter = MIN_MAG_LINEAR_MIP_POINT;
    AddressU = CLAMP;
    AddressV = CLAMP;
    AddressW = CLAMP;
    ComparisonFunc = EQUAL;
};


texts:
I am trying to make a frisbee golf game, and I am stuck on the physics of the frisbee.

I can get the disc to fly, but I have not been able to add spin or make it act the way a frisbee would in real life.

If you can provide some code that would be great, or at least tell me what properties the disc object would need in order for this to work.

The disc has a rigid body with the following set:

Mass = 0.175
Drag = 0
Angular Drag = 200 (I am sure this needs to be changed, just wanted to prevent forward rolling)
User gravity is checked
Is kinematic is unchecked, but changed in a script
Interpolate = None
Collision Detection = Discrete
Constraints are all unchecked

Anyway, any guidance would be much appreciated.


texts: OpenGL GL_TRIANGLE_STRIP creating grid with degenerate triangles / for one draw call

texts:
I need to create a grid ready for GL_TRIANGLE_STRIP rendering with One drawcall - so i need to degenerate the triangles.

I am almost there but missing last row/column and can't figure out why.

My grid is just a :

Position ( self explanatory )
Size ( the x,y size )
Resolution ( the spacing between each vertex in x,y )

Here is the method used to create verts/indices and return them:

int iCols = vSize.x / vResolution.x;
int iRows = vSize.y / vResolution.y;

// Create Vertices
for(int y = 0; y <= iRows; y ++)
{
    for(int x = 0; x <= iCols; x ++)
    {
        float startu  = (float)x / (float)vSize.x;
        float startv  = (float)y / (float)vSize.y;

        tControlVertex.Color    = vColor;
        tControlVertex.Position = CVector3(x * vResolution.x,y * vResolution.y,0);
        tControlVertex.TexCoord = CVector2(startu, startv - 1.0 );

        vMeshVertices.push_back(tControlVertex);
    }
}

// Create Indices
rIndices.clear();

for (int r = 0; r < iRows - 1; r++)
{
    rIndices.push_back(r*iCols);

    for (int c = 0; c < iCols; c++)
    {
        rIndices.push_back(r*iCols+c);
        rIndices.push_back((r+1)*iCols+c);
    }
    rIndices.push_back((r + 1) * iCols + (iCols - 1));
}

And to visualise that, few examples first.

1) Size 512x512 Resolution 64x64, so it should be made of 8 x 8 quads, but i get 7x7 only

2) Size 512x512 Resolution 128x128, so it should be made of 4 x 4 quads, but i get 3x3 only

3) Size 128x128 Resolution 8x8 so it should be made of 16 x 16 quads but i get 15x15 only

So as you can see, i am missing the Last Row and Last Column somewhere.  Where am I going wrong?


texts: How do I set a background image in OpenGL/GLFW?

texts:
I'm writing a simple 2D game with C++ and OpenGL/GLFW, and my current step is to create a menu. I finished with buttons, but I think it looks a little bit boring (with only 4 buttons and a black background).

I want to load an image (.jpg, .tga, .png, etc) to make a more beautiful menu, but I can't find out how. How can I do it?


texts: How can I add different colliders to each body part of a character in Unity?

texts:
I have been using unity game engine for about two weeks now. And I'm very interested in 3D game development. I have been learning basics of Unity and third person games. I saw many tutorials about creating a 3D third person player. They just drag the character into unity and create a capsule collider around the character and freeze the rotation around x and z axis.

So my question is: is it possible to add different colliders to each body part of the character and if so how do I do accomplish that?


texts: How can I transform a 3D triangle to be coplanar with another congruent triangle? - How can I superimpose two congruent triangles?

texts:
I need to transform an equilateral triangle that is lying flat on the xz plane, to become coplanar with another congruent equilateral triangle. I am developing a simple low-poly space exploration game, and my planet generation system requires this.
Terrain chunks are equilateral triangles rather than squares, and they need to be mapped to the faces of an icosphere.
I have found a stack overflow question that outlines a similar problem, but when I tried to implement their solution in Godot, the results were not what I needed. I may have not correctly implemented it, or it might not be an appropriate solution for my problem.
var m0 = Basis()

m0.x = vertices[triangles[10][1]]-vertices[triangles[10][0]]
m0.y = vertices[triangles[10][2]]-vertices[triangles[10][0]]
m0.z = m0.x.cross(m0.y)
m0.y = m0.z.cross(m0.x)

var m1 = Basis()

var p0 = vertices[triangles[10][0]]
var p2 = vertices[triangles[10][0]] + Vector3(get_triangle_size(1,2)/2,0,1)
var p1 = vertices[triangles[10][0]] + Vector3(get_triangle_size(1,2)/1,0,0)

m1.x = p1 - p0
m1.y = p2 - p0

m1.z = m1.x.cross(m1.y)
m1.y = m1.z.cross(m1.x)

var m = m1.inverse() * m0

$Tri.transform.basis = m

The code above is my attempt at implementing the solution in the linked stackoverflow article.
Let $Tri be the triangle that I am moving, and let triangles[10] be a list of vertex indices corresponding to the destination triangle.
To be honest I really don't know how this is supposed to work, but right now, it does not put the triangle in the right place at all. It puts the triangle inside the icosphere, and it's not even rotated properly.
Any help at all would be greatly appreciated, because I am very lost.


texts: Help me adjust this RPG logarithmic leveling formula!

texts:
I'm trying to find a formula that's fits the way I want my player to gain experience and level up. I know this is primarily opinion based but I hope someone can help me!

I've used the following formula as a base, I found it here:

//Calculate level
Level = Math.Max( Math.Floor(6.7f * Math.Log(Experience + 455f) + -40f), 1 );

//Calculate experience for level
Experience = (long)(Math.Exp((Level - -40f) / 6.7f) - 455f);

I wrote a script that will show what it will look like, which is this:

I want to find a way to make it very easy for the player at early levels (let's say until level 15~), and then slowly harder. I'm not sure how to change the formula or if it's even possible! Hope you can help!


texts: Block picking / ray casting through 3d blocks always slightly off

texts:
I've been working on adding a line-of-sight/ray-tracing system to my 3d block-world game. I've tried several different methods and they all work fairly well. At the moment I'm using something similar to what Bukkit uses.

Essentially, using the point of origin (the player location, plus the extra height for the "eye" of the camera), and the current yaw and pitch, I'm looking for every block that the line of sight would pass through.

For the most part it works - however, the "ray" is always slightly off, by roughly half a block or so. What I mean is, as I slowly move my cursor left/right or up/down, the block I'm actually focusing on doesn't "highlight" (for testing, I set it to snow) until the cursor is roughly to the middle. This offset varies a bit based on my angle to the block.

http://d.pr/i/vaZo

It seems like when my cursor is on the left 50% of a block, the block to the left highlights. The top 50% of the block, the block above highlights. Same for right/bottom 50%s.

I'm trying to understand where this discrepancy is coming from. I've been tweaking and toying with code based on the assumption that one of the following is the issue:

The "eye" offset or the player's location are wrong. I'm using the same y offset the camera uses and as far as I can tell from collision, the standing location of the player is accurate
The ray somehow needs adjusted yaw/pitch values? I don't see how, those yaw/pitch values are used for the camera. They should describe the exact direction the ray needs
The "normalization" code for the vector is wrong. I've found essentially same code in multiple examples, and it seems like it doesn't round/cast values, so I shouldn't be losing anything

I'm looking for advise on:

What values are the most likely cause for a half-block offset?
or, how do I fix?

The player's camera is set like this:

GL11.glLoadIdentity();
GL11.glRotatef(pitch, 1.0f, 0, 0);
GL11.glRotatef(360.0f - yaw, 0, 1.0f, 0);
GL11.glTranslatef(-position.x, -position.y - EYE_HEIGHT, -position.z);

EYE_HEIGHT is 1.8f

The "direction" vector is normalized like this:

Vector vector = new Vector(0,0,0);
vector.setY( (float)-Math.sin(Math.toRadians(pitch)) );
float v = (float)Math.cos(Math.toRadians(pitch) );
vector.setX( (float)(Math.sin(Math.toRadians(yaw))*-v)  );
vector.setZ( (float)(Math.cos(Math.toRadians(yaw))*v)  );

And the player's location is essentially just a `Vector3f.

I've found several alternate methods of calculating the right info here on gamedev, but the code I have is so close it doesn't seem worth ditching. Though I will if needed, lol.


texts: I was wondering if I could get a player sprite effect similar to the one in this video using SDL (without openGL).  If not, does anyone know how I might achieve that effect using SDL/OpenGL?


texts:
I have some understanding problem concerning quaternions.

In order to have my world object rotate in the correct way, I need to invert their quaternion rotation while refreshing the object world matrix.

I create the object rotation with this code:

Rotation = Quaternion.RotationMatrix(Matrix.LookAtRH(Position, Position + new Vector3(_moveDirection.X, 0, _moveDirection.Y), Vector3.Up));

and refresh the object World matrix like this:

Object.World = Matrix.RotationQuaternion(Rotation) * Matrix.Translation(Position);

This is not working; it makes the object rotate in the opposite way compared to what it should!

The is the way that makes my object rotate correctly:

Object.World = Matrix.RotationQuaternion(Quaternion.invert(Rotation)) * Matrix.Translation(Position);

Why do I have to invert the object rotation?


texts: Using Unity built-in sprites programatically

texts:
I'm trying to figure out how to use the "Panel" built in resource in a game I'm making. I've been able to figure out some potential solutions, but I can't quite figure out how to put all of the pieces together.

panelImage.sprite = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/InputFieldBackground.psd");
panelImage.sprite = Resources.GetBuiltinResource(typeof(Sprite), "Resources/unity_builtin_extra/Background.psd") as Sprite;

The first produces the button sprite, which is almost what I want, but not quite. The second doesn't work at all. I'm missing some small piece of what it takes to make this work, but I can't quite figure it out. How can I use the panel background programmatically?


texts:
I would very much like to build a game that is known as 'Unblock' or 'Yellow Out'. It is a puzzle game in which the task is to move a car out of a parking space by moving other cars in certain directions.

These are links where the game can be played:

Yellow Out
Unblock

My questions concerning this game are:

Is this game actually licensed? I see it's available under two names (perhaps even more). Does this mean the game idea can be used freely?
Is there an article about it? I have not been able to find it on Wikipedia. I would like to gather some information about the game so as to understand more details of it.
Is there some database with puzzles available? I can just check the puzzles of existing games, but that's a pain because I have to finish a level to get on to the following one. I was wondering whether there is a general list of puzzles somewhere.

Thanks!


texts: How would I make a bullet shoot from my player to my mouse.

texts:
So far I've created an object called obj_mouse. And my plan is whenever the player left clicks, it spawns a bullet from him toward where ever the mouse is pointing. I've got the concept down, but I'm struggling getting it to work.

Extra bits of code I'm messing around with to try and get it to work:

    bullet=instance_create(x,y,obj_bullet)
with (bullet) {
move_towards_point(mouse_x,mouse_y,5)
image_angle=direction
}

point_direction(obj_mouse,obj_mouse,obj_mouse,obj_mouse)
image_angle=direction

(In the above code, I havent attempted to specify to the program that I want the bullet to go in the direction of obj_mouse, or rather, just the mouse. The above code works, and bullets do shoot, however the player must have the mouse on the players sprite for it to work.)

Thank you in advance for any advice given.


texts: How to clear a buffer to 1.0 instead of 0.0 in OpenGL?

texts:
Using glClear() you can set the buffer specified by the parameter to 0.0. This is useful say if you want pixels not covered by models to be black. Because vec3(0.0, 0.0, 0.0) results in black.

But for the depth buffer, clearing means to set it to the maximum value 1.0 since you don't want pixels not covered by models to have the depth 0.0 which is the camera's position but to have the depth 1.0 which means as far away as possible.

So how can I clear the depth buffer to 1.0 or come over this issue in another way?


texts:
My main question is related to 3D game design for Unity, but please let me introduce my idea so that you can understand what I really mean.

I am very eager to develop an adventurous - travel 3D game (Unity), where the main character is given some kind of task in country A and if he deals with it, he goes to the upper level, which is in another country and so on.

I have never developed a computer game before. I have knowledge of c# and a bit of java (for the programming part of the game). But I really don`t know where to start with the design. I have to think of a main character, episodic characters, environment and distinctive buildings for each country in 3D (for e.g. The Eiffel Tower in Paris, The Colloseum in Rome, The Great wall of China etc. ).

My question is: where to begin with the 3D design of the characters, the cities and the buildings? Can you please give me step-by-step instructions so that I can do something good and meaningful?

I know that Blender is a good option for 3D modeling, but is it the only thing needed for the 3D game design? I have experience with Adobe Illustrator, so can I use it to some extent in this case (for 3D game elements)?

Can I use Illustrator then import it in Blender and finally import the Blender product in Unity?

I accept every advice given. I really need someone to explain these things to me because for now I am really puzzled and not orientated from where to begin.
Thank you!


texts: Correct order of rotation and translation

texts:
Trying to get this right in openGL:

1) glRotate( cameraRotation )

2) glTranslate( -cameraPosition )

3) glRotate( objectRotation )

4) glTranslate( objectPosition )

5) Draw Object

is that right?


texts: How to remove Sharp Edges on Texture in Libgdx Game

texts:
I am making the above Libgdx game but I have come across the problem of really sharp images for my background if I zoom out of the world.

As you can see on the screenshot there are really sharp edges that appear surrounding the texture of the purple background.

How can I make the Texture blend well with the surrounding?


texts: Mouse position to world position for Camera

texts:
I am working on a case where when the mouse is moved upwards, the camera must also move upwards.

I understand that for mouse picking we perform ray casting along a plane. I think my case is little different, the camera movements(x,y,z) must be linked with mouse movement(x,y) in all directions.

I am using the OGRE 3D engine.


texts:
I am trying to pass UIImage to GLSL shader. The fragment shader is:

varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2;

void main()
{
  highp vec4 color = texture2D(inputImageTexture, textureCoordinate);
  highp vec4 color2 = texture2D(inputImageTexture2, textureCoordinate);

  gl_FragColor = color * color2;

}

What I want to do is send images from camera and do multiply blend with texture. When I just send data from camera, everything is fine. So problem should be with sending another texture to shader. I am doing it this way:

- (void)setTexture:(UIImage*)image forUniform:(NSString*)uniform {

  CGSize sizeOfImage = [image size];
  CGFloat scaleOfImage = [image scale];
  CGSize pixelSizeOfImage = CGSizeMake(scaleOfImage * sizeOfImage.width, scaleOfImage * sizeOfImage.height);

  //create context
  GLubyte * spriteData = (GLubyte *)malloc(pixelSizeOfImage.width * pixelSizeOfImage.height * 4 * sizeof(GLubyte));
  CGContextRef spriteContext = CGBitmapContextCreate(spriteData, pixelSizeOfImage.width, pixelSizeOfImage.height, 8, pixelSizeOfImage.width * 4, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast);

  //draw image into context
  CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, pixelSizeOfImage.width, pixelSizeOfImage.height), image.CGImage);

  //get uniform of texture
  GLuint uniformIndex = glGetUniformLocation(__programPointer, [uniform UTF8String]);

  //generate texture
  GLuint textureIndex;
  glGenTextures(1, &textureIndex);
  glBindTexture(GL_TEXTURE_2D, textureIndex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  //create texture
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixelSizeOfImage.width, pixelSizeOfImage.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);

  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, textureIndex);
  //"send" to shader
  glUniform1i(uniformIndex, 1);

  free(spriteData);
  CGContextRelease(spriteContext);
}

Uniform for texture is fine, glGetUniformLocation function do not returns -1. The texture is PNG file of resolution 2000x2000 pixels.

PROBLEM: When the texture is passed to shader, I have got "black screen". Maybe problem are parameters of the CGContext or parameters of the function glTexImage2D

Thank you


texts: Why are my 2D world click-positions offset after camera movement?

texts:
I'm writing a 2D game engine. I need to add a camera to my world that can zoom in and out as well as move away from its initial position at (0,0) at the center of the world.

The main issue can be seen in this video. When the camera hasn't yet moved (still at 0,0), I can click anywhere in the visible world and the click is mapped to the correct world position. I can even zoom and everything including the mouse position is scaled correctly. However, the moment I move the camera, the position becomes offset by a percentage of the camera movement. (This is clearer in the video.)

I have tried calculating the draw position and world mouse position in many different ways, but I always get the same issue.

What might be wrong?

Here's the code for both object position to screen position and mouse position to world position conversion:

public Vector2 GetDrawCoord(Vector2 position)
{
    return new Vector2(((position.X - cameraCenter.X)) * zoom + graphics.Viewport.Width / 2,
        graphics.Viewport.Height - ((position.Y - cameraCenter.Y) * zoom + graphics.Viewport.Height / 2));
}

public Vector2 GetClickCoord(Vector2 position)
{
    return new Vector2((position.X - graphics.Viewport.Width / 2 + cameraCenter.X) / zoom,
        (graphics.Viewport.Height / 2 - position.Y + cameraCenter.Y) / zoom);
}

Update:

New code:

Vector3 vec = graphics.Viewport.Unproject(new Vector3(position.X, position.Y, 0f),
            Matrix.CreateOrthographic((float)graphics.Viewport.Width, (float)graphics.Viewport.Height, 0f, 0f),
            cameraMatrix,
            Matrix.Identity);


texts: How to detect whether an Object came to sleep at a specific position?

texts:
I'm currently writing a small game with box2dweb and I need some direction for this: I'm throwing a Box and have to hit a specific place and trigger an event when the object that's been thrown isn't moving anymore, "fell asleep" so to say.

What's the proper way / best practice for this?

I'm currently thinking of asking the b2World whether an Object is within a specific AABB and then wait a few seconds, check if it's still there and then trigger the event. But this seems to me like the roundabout way and the object might still be moving inside of that AABB and eventually even drop out of the AABB.


texts: How do I rotate and flip 2D sprites stored in a 1D array of pixels?

texts:
I am using a 1D array of pixels for rendering in 2D in java. I am interested in rotation (in radians) and mirroring across the x and y axes. The desired result looks something like this:

Public void render(Sprite sprite, int x, int y, double rotation, boolean xFlip, boolean yFlip) {}

I am not using any libraries for the current project. The information that I have gleaned is that I must somehow multiply the points of my pixels with a transformation matrix. I am familiar with matrices (outside of a programming context) and am ok with rigorous mathematics.

How do I rotate and flip 2D sprites with a 1D array of pixels?

EDIT
The sprite class is almost exclusively a wrapped array of pixel data.
In my Screen class:

image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels  = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

and then

g.drawImage(image, 0, 0, getWidth(), getHeight(), null);


texts: How to handle complex inputs in 2D platform game?

texts:
I am trying to add keyboard control for my character in 2D platform game with JavaScript. The character can walk, dash and jump. Here is my current code:

if(keyboard['LEFT']) {
    //walk to left
    //...
} else if (keyboard['RIGHT']) {
    //walk to right
    if(keyboard['SHIFT'] && !jump) {
        //dash
    }
    if(keyboard['JUMP']) {
        //jump to right
    }
    if(keyboard['SHIFT'] && keyboard['JUMP']) {
        //dash and jump (move further and faster)
    }
    if(keyboard['JUMP'] && keyboard['SHIFT']) {
        //hold the right key, pressed jump key, and then pressed shift key
        //it expected to jump to right here, because character can not dash
        //in midair, but it will conflict the if condition above.
    }
} else if (keyboard['JUMP'] && onGround) {
    //jump
} else if (keyboard['SHIFT']) {
    //dash
    if(keyboard['JUMP']) {
        //dash and jump
    }
}

I am confused that there are many if() else() statement in my code, and it seems that I need to control the order of keyboard inputs.Is there an easy way to handle that?Am I going the right way? If not, what is the common way to achieve that? Please, Any help would be appreciated.


texts:
Writing for android, but this is an abstract question for any OO language.  Is there a "best-practice" for implementing a TechTree?

Here is an example:

    Vegetation  ->v     Strawberries        ->      BioDome
    Livestock   ->      Biomass

In this example, both Vegetation and Livestock are required for Biomass, but only Vegetation is required for Strawberries.

I have brainstormed a handful of implementations, but I'm not very confident with any of them.  I will probably be loading the techs from XML, if that matters.

Is there a "best-practice"for implementing tech trees?


texts: Why do meshes show up as bones in the Model class?

texts:
Right now I'm working on a 3D game and I've come across something very weird. When I created the model in Blender, I added an armature named "MyBone" to the stage and attached a cube ("MyCube") to it, so that when I move the armature, the cube moves with it. I exported this as an FBX and loaded it as a Model object.

What I expected to see was:

But what I got was this:

I'm really confused. Why is the mesh I created showing up in the bone list? And what's Root Node?

Here are the .blend and .fbx files: here or here.

Thanks.


texts: Unity2D - How to leave and come back to the same scene properly?

texts:
I am new to game development and for exercise I made endless runner where everything is generated randomly from prefabs and both player and obstacles are being destroyed once they are off the screen. There are two scenes - Start and Game. At the Start scene you can click on Play button which will take you to the Game scene and you can mute the sound.

When I start the game and I click on the Play button it loads the Game scene perfectly and game runs and works just fine. When player dies the game over window is shown. From there two options are available - either go to the Start scene or play the game one more time.

If I choose to play one more time everything works perfectly. But if I choose to go to the Start scene and then click on Play button to play the game then once the Game scene is loaded the player and the obstacle game objects are not being generated and floor and background Quads are not being resized properly to fit the screen. And I get the following error -

MissingReferenceException: The object of type 'RecycleGameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
ObjectPool.NextObject (Vector3 pos) (at Assets/Scripts/ObjectPool.cs:28)

My question is  - what can I do so that every time I come back to the scene everything is being loaded just like the first time?

I am currently loading scenes with this code:

SceneManager.LoadScene("Start");

And this is the ObjectPool class:

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

public class ObjectPool : MonoBehaviour {

    public RecycleGameObject prefab;
    private List<RecycleGameObject> poolInstances = new List<RecycleGameObject>();

    private RecycleGameObject CreateInstance(Vector3 pos)
    {

        var clone = GameObject.Instantiate(prefab);
        clone.transform.position = pos;
        clone.transform.parent = transform;

        poolInstances.Add(clone);

        return clone;
    }

    public RecycleGameObject NextObject(Vector3 pos)
    {
        RecycleGameObject instance = null;

        foreach(var go in poolInstances)
        {
            if(go.gameObject.activeSelf != true)//here I get the error
            {
                instance = go;
                instance.transform.position = pos;
            }
        }

        if(instance == null)
        {
            instance = CreateInstance(pos);
        }

        instance.Restart();

        return instance;
    }

}


texts: How to implement stress/strain mechanics in voxel terrain?

texts:
I am in the process of developing a Minecraft-like world where the terrain is divided into voxels. However, I would also like for unstable configurations of landscapes to collapse predictably. For example, an overhang that is too heavy would fracture and break off at 'high stress' voxels, as would a pillar formation with an asymmetrically eroded base. I was thinking about adding a 'stress vector' field to each voxel in the terrain, and doing the following (pseudocode):

foreach voxel in terrain
    foreach neighbor in voxel.neighbor_voxels()
        if magnitude(voxel.stress - neighbor.stress) > stressThreshold
            detach_voxels(voxel, neighbor)

But the problem is that I don't know how I would go about calculating these individual stresses. Is there some kind of FEA-based algorithm specialized for voxel discretizations that I can use to calculate the stresses on a per-voxel basis? Or am I approaching this all wrong and there's some other way to do this?


texts: How do I efficiently choose the terrain chunks to render based on the player position?

texts:
Well, I have an array with all the terrains. How do I render them? I just add them to a List of terrains that are sent to the Renderer. There, every terrain of the list is rendered.

The problem is that if I add all the terrains of the array to the list (let's call it toRenderList), my computer explodes because of the number of terrains.

What I've tried to achieve it's to add to the list ONLY the terrains that are into a certain range. This is what I've done:

private static Terrain[][] terrains;
private List<Terrain> toRenderList;
private static final int NUMBER_CHUNKS = 3; //Number of terrains that are added to the list.

public void update(Player player){
    if(player.hasChangedTerrainPosition()){
        toRenderList.clear();
        for(int x = player.getTerrainPosition()[0]-NUMBER_CHUNKS;
            x == player.getTerrainPosition()[0]+NUMBER_CHUNKS; x++){
            for(int y = player.getTerrainPosition()[1]-NUMBER_CHUNKS;
                y == player.getTerrainPosition()[1]+NUMBER_CHUNKS; y++){
                terrainList.add(terrains[x][y]);
                System.out.println("Terrain "+x+","+y+" added!");
            }
        }
    }
}

Just to clarify, the method player.getTerrainPosition returns a int[] with the current terrain coords in where the player is standing. The method player.hasChangedTerrainPosition returns true if the player has changed of  terrain.

The problem of this method is that for example if the player is in the position [0,0] it pops an error of ArrayIndexOutOfBounds because of a negative number.

I don't know if I've been specific. This is more basic Java than GamePrograming, but any help will be appreciated. Thanks!


texts: I am wanting to make a 3d RPG with unity, and I'm in the planning phase. For the camera I decided to make it GTA style. I want the camera to be rotated around the player without effecting the movement of the player. If anyone can give any pointers on this, I would be very grateful.


texts: Which texture do I bind to when implementing multi-texturing?

texts:
I have been having some issues getting multi-texturing to work using OpenGL ES 1.1. I have two PKMs - one with RGB's and one for alphas and I am trying to combine the two as below:

            int rgbTexture = textureId[0];

            gl.glActiveTexture(GLES10.GL_TEXTURE0);
            gl.glBindTexture(GLES11.GL_TEXTURE_2D, rgbTexture);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_MODULATE);

            ETC1Texture etcTexture = ETC1Util.createTexture(inputStream);
            ETC1Util.loadTexture(GLES11.GL_TEXTURE_2D, 0, 0, GLES11.GL_RGB, GLES11.GL_UNSIGNED_SHORT_5_6_5, etcTexture);

            int alphaTexture = textureId[1];

            gl.glActiveTexture(GLES11.GL_TEXTURE1);
            gl.glBindTexture(GLES11.GL_TEXTURE_2D, alphaTexture);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_COMBINE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_COMBINE_RGB, GLES11.GL_REPLACE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC0_RGB, GLES11.GL_PREVIOUS);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND0_RGB, GLES11.GL_SRC_COLOR);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_COMBINE_ALPHA, GLES11.GL_MODULATE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC0_ALPHA, GLES11.GL_TEXTURE);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND0_ALPHA, GLES11.GL_SRC_ALPHA);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_SRC1_ALPHA, GLES11.GL_PREVIOUS);
            gl.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_OPERAND1_ALPHA, GLES11.GL_SRC_ALPHA);

            InputStream inputStreamAlpha = fileIO.readAsset(fileName + "_alpha.pkm");
            ETC1Texture etcAlphaTexture = ETC1Util.createTexture(inputStreamAlpha);
            ETC1Util.loadTexture(GLES11.GL_TEXTURE_2D, 0, 0, GLES11.GL_RGB, GLES11.GL_UNSIGNED_SHORT_5_6_5, etcAlphaTexture);

One of the problems that I am having is I don't know which texture ID to bind to when rendering this multi-texture and if I should make GL_TEXTURE0 or GL_TEXTURE1 active when rendering. The code above is from the load() method within my Texture class. On startup, I load all of the necessary textures using the code above. I then keep a reference to these Texture objects while I still need them and when I want to render them, I bind to the ID of the rgbTexture (as shown above) and I make GL_TEXTURE0 active. Is this correct? Should I be binding to the alphaTexture's ID? Should GL_TEXTURE1 be active when rendering? Or both? Or is multi-texturing supposed to happen at render time? Ideally I am looking for a solution that combines these textures into one at startup and then when rendering, I just bind to this one combined texture.


texts: Should response be tied to request in a multiplayer game?

texts:
I wonder if server responses on client operation requests should be tied by some operation id?

Tied would be when:

1.Client app sends request to server to e.g. buy item X, and sets operation id as ID.

2.Server responds with operation id and true or false.
This would mean that operation with that id was successful or not.

Untied example:

1.Client app sends request to server to e.g. buy item X

2.Server responds with just an updated data of item X, where new item owner would be mentioned.
This way client can check if owner name is equal to it's own name and if true, assume that item was bought successfully. Same response data could be sent to other clients, to let them know that item X was bought by someone.

Which approach is better?

IMHO untied is better and simpler in implementation, but it feels like there can be so many edge cases which I don't see right now.


texts: Unity3D setting blend mode in shader using vertex data

texts:
I'm porting a game from iOS / Obj-C / OpenGL ES 2.0 to Unity.

I have a procedural mesh script that generates a batch of quads that need to blend together to create a game board.  Some of the quads add a highlight effect, others on top of those darken the scene.  This is handled with the blend mode and the color of the object.

In the old version I did things inefficiently and just drew each quad individually, as needed setting the blend mode (glBlendFunc) and a color uniform.  I batched similar things as I could.

In Unity3D rather than having 500 sprite gameObjects which IMO would be difficult to manage.  I have one gameObject with a mesh = one draw call. I use per vertex color attribute instead of a uniform to set colors for each quad/sprite.  But I want to also set the blend mode per quad by using vertex data.  I'm sending the blend mode as uv2 data.

I found this question.  See the second answer: http://answers.unity3d.com/questions/399074/change-blend-mode-from-outside-shader.html

Which says you can do this:

Pass {
    Blend [MySrcMode] [MyDstMode]
}

But in the example MySrcMode and MyDstMode are shader properties (uniforms) and again would set the blend mode for the entire draw call.  I want to change it per quad which would have to be done per fragment.

I understand GLSL shaders.  They make sense to me.  But Unity shaders are still a bit mysterious.  The unity docs aren't getting through to me and I can't find any good tutorials on really how they work and what gets called in what order.  I tried:

Blend [texcoord1.x] [texcoord1.y]

But that didn't work. (Meaning that it's not getting a value for texcoord1 there.) My Blend is above the Pass{}.  Moving it inside the Pass either is the same or produces an error depending where it goes.

My other option would be to do something like a gl_LastFragData to fetch the current fragment and do my own per fragment blending.

Or do I have to pull out the quads that use a different blending into another game object.  Which would mean having geometry sorted into game objects based on their blending mode and not their behavior or the script that creates and manages them.


texts: How to program (architecturally/organize) a set of customizable changes to a game?

texts: The floor of my game (tower defense) is composed by a set of cubes. I wish to change these on some of the waves. I have a list of the changes that need to be made on each wave in a floorController class. However, in order to decide which floor cubes should appear or disappear on each round, I had to assign each cube a bool for each wave (if this is set to true the floor changes in that wave). However this process is tedious and not ease to change and customize in order to experiment with the level. From an architectural programming perspective how can I better structure this system?


texts: Is it possible to have a fixed camera without a CameraSubject?

texts:
I have created a very simple script to set up a fixed camera with no subject.  In other words, I want a camera in a static position looking down at the world (a top-down style camera that doesn't follow anything), but regardless of what I do, the camera always attaches to a "Humanoid".

Is there a way to prevent this?

For reference, here is my script, which I name CameraScript and place in the StarterPlayerScripts group:

local cameraHeight = 150

local camera = game.Workspace.CurrentCamera
local player = game.Players.LocalPlayer

repeat
        wait()
until player.Character

local function setupCamera()
    camera.CameraType = Enum.CameraType.Fixed
    camera.CameraSubject = nil
    camera.CFrame = CFrame.new(Vector3.new(0,cameraHeight,0), Vector3.new(0,0,0))
    print(tostring(camera.CameraSubject))
end

setupCamera()


texts: Read from OpenGL texture to Bitmap in C#

texts:
I want to read a texture pixels from texture id (associated with some FBO) to bitmap object in opengl (opentk) in c#
But it throws an exception says:

System.AccessViolationException occurred
  HResult=0x80004003
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=OpenTK

The code:

public Bitmap GetTexture(int AttachmentIndex)
        {
            if (AttachmentIndex > fbo_colorBuffer.Count - 1)
                throw new IndexOutOfRangeException();

            Bitmap bitmap = new Bitmap(width, height);
            BitmapData bits = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            BindToRead(ReadBufferMode.ColorAttachment0 + AttachmentIndex);
            GL.ReadPixels(0, 0, width, height, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float, bits.Scan0);
            bitmap.UnlockBits(bits);

            return bitmap;
        }

public void BindToRead(ReadBufferMode Mode)
        {
            GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, fbo_id);
            GL.ReadBuffer(Mode);
        }


texts: SerializeField UntiyEvent not properly saving modifications in EditorWindow

texts:
I'm making a node editor in Unity using an EditorWindow, I'm currently trying to make it so designers can add their own methods to a node using serialized UnityEvents; but I haven't been able to get it to function properly.

SerializedObject serializedObject = new SerializedObject(selectedNode.NodeState);

SerializedProperty property = serializedObject.GetIterator();
property.Next(true);

while (property.NextVisible(false))
{
    EditorGUILayout.PropertyField(property);

}
serializedObject.ApplyModifiedProperties();

serializedObject.Update();

The above code runs through all necessary fields of the class so the user can modify them.

Everything functions perfectly with the exception of UnityEvents. They almost do as I intend them to do, except they don't preserve the variable inputs of inserted object's method. If I keep working within the editor window they stay, but if I close the window and re-open the inputted variable resets.

I thought this may be caused by an issue somewhere else in my code, but all other fields work fine.


texts: How do I enfroce efficiency concerning thread granularity?

texts:
Lately, I've been thinking of ways to use multi-threading to improve the speed of different parts of a game engine. What confuses me is the appropriate granularity of threads, especially when dealing with single-instruction-multiple-data (SIMD) tasks.

Let's use line-of-sight detection as an example.  Each AI actor must be able to detect objects of interest around them and mark them.  There are three basic ways to go about this with multithreading:

Don't use threading at all.
Create a thread for each actor.
Create a thread for each actor-object combination.

Option 1 is obviously going to be the least efficient method.  However, choosing between the next two options is more difficult.  Only using one thread per actor is still running through every object in series instead of in parallel.  However, are CPU's able to create and join threads in the granularity posed in Option 3 efficiently?  It seems like that many calls to the OS could be really slow, and varying enormously between different hardware.


texts: XY Location scaling with varying density screens

texts:
I have a phone with resolution H=1280,W=720,Density=2
I have a tablet with resolution H=1216,W=800,Density=1.331

I drew a rectangle on my phone with corners Left,Top (-1.6,1.55), Right,Bottom (1.6,-1.65).
If I want to draw very similar rectangle on tablet (the gap of edges from screen ends look almost same), what would the formula be to calculate the four corners?

Given:
* The origin is always at center of screen. (because I don't know how to change it in Opengl ES 2.0 :-/ )

Shader code:

String vertexShaderSource = "attribute vec4 a_Position; uniform mat4 uMVPMatrix; void main() { gl_Position = uMVPMatrix * a_Position; }";
String fragmentShaderSource = "precision mediump float; uniform vec4 u_Color; void main() { gl_FragColor = u_Color; }";

OpenGL setup code:

@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    this.W = width;
    this.H = height;

    glViewport(0, 0, width, height);

    //initialize rectangle...

    Matrix.setIdentityM(mProjMatrix, 0);
    Matrix.setIdentityM(mViewMatrix, 0);
    Matrix.setIdentityM(mMVPMatrix, 0);

    float aspect = width > height ? (float)width / height : (float)height / width;

    // Setup our screen width and height for normal sprite translation.
    // ortho is converting 3d to 2d - z is 0
    if (width > height) {
        Matrix.orthoM(mProjMatrix, 0, -aspect, aspect, -1, 1, 3, 7);
    } else {
        Matrix.orthoM(mProjMatrix, 0, -1, 1f, -aspect, aspect, 3, 7);
    }

    // Set the camera position (View matrix)
    Matrix.setLookAtM(mViewMatrix, 0,
                        0f, 0f, -3f, // eye
                        0f, 0f, 0f, // center
                        0f, 1f, 0f); // up

    // Calculate the projection and view transformation
    Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mViewMatrix, 0);
}

@Override
public void onDrawFrame(GL10 gl) {
    glClear(GL_COLOR_BUFFER_BIT);

    // view transformation
    glUniformMatrix4fv(_uMVPMatrix, 1, false, mMVPMatrix, 0);

    m_vertexBuffer.position(0);
    glVertexAttribPointer(m_a_Position, POSITION_COMPONENT_COUNT, GL_FLOAT, false, 0, m_vertexBuffer);

    glDrawArrays(GL_LINE_LOOP, 0, 4);
}

I do not have any formula. Has anybody got any idea?


texts: What is Opengl ES ? What is gl and GLES20 mean?

texts:
I am new in opengl. I saw tutorial some have gl at the beginning and some have GLES20 at the beginner and some has GL10.

What are the differences? Is GLES20 mean opengl es2 whereas GL10 mean version 1


texts:
I'm working on a battle algorithm for a text-based game and I stumble when it comes to randomly distributing attacks on a set of units.

E.G, 100 archers shoot 100 targets at the same time. I thought of doing like this :

The 100 targets are considered as a single block
The arrows are distributed inside
The units hit the same number of times are grouped together.
I manage the life of each new group
Repeat on each new group if necessary

I can distribute the arrows (step 2) and get the result (step 3) through a loop, but with many armies composed of millions archers, computing time & memory consumption becomes a problem.

// Step 2
const targets = new Array( 1000000000 );
targets.fill( 0, 0, 1000000000 );
const arrows = 1000000000;
for( let i = 0; i < arrows; i++ ){
    const index = Math.floor( ( Math.random() * arrows ) );
    targets[ index ] += 1
}
//Step 3
const result = []
targets.forEach( value => {
    if( value ){
        if( result[ value ] ) result[ value ] += 1
        else result[ value ] = 1
    }
} )

Is there another way to solve this problem ? I believe that with large numbers, directly calculating the most likely scenario may be a good option. Unfortunately, I do not know anything about probabilities.


texts:
I have a pretty simple character rig animation. How can I export the raw data of that animation?

I'm looking for some way to export a raw text array of data that tells exactly what every joint does on every frame. This means rotation, translation, etc.

EDIT:
Thanks for the answers so far. We are looking for a way to get something like this:
This would be one joint of a 14 frame animation.

 <joint>
      <name> rightShoulder </name>
      <xPos>12 14 16 18 19 20 21 24 26 28 32 34 36 38 </xPos>
      <yPos>100 99 98 97 96 95 94 93 92 91 90 91 92 95 </yPos>
 </joint>

We are also trying to keep the file lightweight. So we will be ONLY including this data, no meshes, cameras or anything else. I've been looking into .DAE but it seems pretty heavy.

Any suggestions? If nothing standard works, how would one go about writing their own Maya exporter? Does something like this seem possible?


texts: Unity 2019.3 - Tilemap colliders 2D + Componsite colliders + Platform effectors

texts:
I am using tilemaps to create my own platform game. This is what I had in the first place.

This was working fine in first place, but is an issue. Sometimes, the enemies get stuck while running along the platforms. This was probably due to a similar issue that I had, when the player was getting stuck on the walls. It was solved by adding a composite collider. So I did the same to solve this problem. With the composite, it was looking like this:

This solved the issue too. But now comes the catch. Those elements are also platforms, meaning that I have to add a platform effector. And while this works, there is a small edge case...

If I am in a height where I do not reach the top of the platform, but can reach the bottom part, somehow it can stand on it. This was not happening before using the composite collider 2D.

Why is this happening? How can avoid this issue?

I am using Unity 2019.3.9f1


texts: Is it a good move to disable windows' file-caching capabilities (via I/O completion ports) for resource loading in a game environment? Most games will do their own resource management and caching anyways, so the OS will probably cache it a second time. Of course, you don't get the caching across the process' lifetime, but that's usually not a big downside. On the other hand, it probably makes file loading times more predictable - so you can actually give accurate load-time predictions.


texts: Unity: Adjusting the camera so that the scene view and the game view look same

texts:
when I make any object I'm able to see that by other side in the game view. And this troubles me in adjusting the objects.

So can anyone help me to adjust the main camera in such a way that views of both game and scene look the same?

Thanks in advance.


texts: Unsupported API version on Spigot 1.14 snapshot

texts:
I'm (trying to) develop a plugin for Spigot Minecraft 1.14.2. I have tried putting both api-version: 1.14.2 and api-version: 1.14.2-R0.1-SNAPSHOT in my plugin.yml file however it always comes up with the following error:

org.bukkit.plugin.InvalidPluginException: Unsupported API version 1.14.2-R0.1-SNAPSHOT
    at org.bukkit.craftbukkit.v1_14_R1.util.CraftMagicNumbers.checkSupported(CraftMagicNumbers.java:252) ~[spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:333) ~[spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:252) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.loadPlugins(CraftServer.java:347) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.reload(CraftServer.java:803) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.Bukkit.reload(Bukkit.java:576) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:27) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:149) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.dispatchCommand(CraftServer.java:707) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at org.bukkit.craftbukkit.v1_14_R1.CraftServer.dispatchServerCommand(CraftServer.java:692) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.DedicatedServer.handleCommandQueue(DedicatedServer.java:433) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.DedicatedServer.b(DedicatedServer.java:397) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.MinecraftServer.a(MinecraftServer.java:956) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at net.minecraft.server.v1_14_R1.MinecraftServer.run(MinecraftServer.java:801) [spigot-1.14.2.jar:git-Spigot-df0eb25-649921e]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_212]

however I am using the correct API version. Whenever I change the api-version in plugin.yml the error message changes accordingly.

What have I done wrong?

EDIT: https://termbin.com/u5a8 - full server log
plugin.yml:

name: choruschaos
main: com.cospox.choruschaos.main
version: 0.1
api-version: 1.14.2-R0.1-SNAPSHOT
commands:

main.java:

package com.cospox.choruschaos;

import org.bukkit.plugin.java.JavaPlugin;

public class main extends JavaPlugin {
    // Fired when plugin is first enabled
    @Override
    public void onEnable() {
    }
    // Fired when plugin is disabled
    @Override
    public void onDisable() {

    }
}


texts:
What practical choices do I have in order to rotate a camera in 4D space? I would like to make it as intuitive as possible.

A camera in 3D space can be represented by

a point where it is located
the forward vector (movement using the [w] and [s] buttons)
the left (movement using the [a] and [d] buttons)
the up vector (eg. [space] and [ctrl])

In 4D space, the an additional axis is added:

the fourth axis vector (eg. [q] and [e])

All of the vectors remain orthogonal to eachother. So the movement is trivial.


texts: What interchange format should I use for e.g. subtitles and UI texts?

texts:
Are there any standard formats that can be used as the source material for game texts (i.e. subtitles, UI texts, etc.)? I can think of the following constraints:

at least some style effects (e.g. bold, italics)
at least some format string support (e.g. you found %d gold, you found {count} gold)
be translator-friendly: either easy to grasp, or standard enough that translation companies may already have experience with it

I know about the following but none of them appear to support format strings. Are there any industry standards for that or does every game or engine roll their own format?

UE4 uses a custom rich text format (example: Hello <RichText.Emphasis>everyone</>!)
Unity uses its own HTML-like format (example: Hello everyone!)
the srt format uses HTML-like syntax, too (example: Hello everyone!)
BBCode is another popular format (example: Hello [b]everyone[/b]!)


texts:
I created a project based on the Top Down Example.

What is happening is that there is an area just above my character where I can not click.

Image showing location where the mouse is and soon after, when I move it a little to the left it disappears:

By the minimap you can see that the game recognizes as if the mouse was on top of the character, very close.

I went to test to see if this happened in all Top Down Examples, but it does not happen:

I've modified the position of the camera a bit in this project where I'm having problems (image 1). Is there a non-clickable area defined based on the camera, to prevent the player from clicking the location where the character is? And with the change of position the area is no longer equivalent to the position of the character?

This area in red I can not click:

I have not changed anything that has to do with the mouse in the character's blueprint:

What is going on?

EDIT 1 (tests done based on some comments to clarify the question and to verify possible cause of the problem)

I pressed P to see if there was any area of the map where there could be no click:

See I can put my mouse right below the character, and even click:

From there up the mouse does not appear, and obviously I can not click:

Location where the mouse appears again and what I can click:

These 3 images were captured in the character's home position without moving it. But the problem persists wherever the character is.

Through the test I did below, I prove that the problem is directly related to the position the character is in:

The green question marks the spot where my mouse is.

EDIT 2 (I think I discovered the problem)

I read DMGregory's comment again and went to look at the collider, it was small and it already existed before the problem happened.

I started the game and paused. I came across this image:

I created this sprite to appear on the minimap, I believe that may be the cause of the problem. How to make the mouse skip it? Without having to simply upload it?


texts: Slick2D : translate -> scale -> translate doesn't return to the old position

texts:
I am trying to implement zoom using Slick2D library.

As I understand, to zoom something on non (0,0) coordinates, we need:

translate so the target point is in (0,0)
apply scale factor
translate the target point back from (0,0)

Code example :

 aGraphics.translate(-width/2, -height/2);
 aGraphics.scale(2,2);
 aGraphics.translate(width/2, height/2);

The issue is, as far I understand, that the scale factor is applied to the translation too. To compensate this, I have use the next code :

 aGraphics.translate(-width/2, -height/2);
 aGraphics.scale(2,2);
 aGraphics.translate(width/4, height/4);

Is this expected behaviour for graphics ? Can I workaround the above effect using push/pop matrix ?


texts: Blurry background sprite, other sprites fine

texts:
Why is the background blurry, but all the other sprites fine?

The background sprite has the same settings as the others. It's on the same Z position (0). It happened after I made some changes to the original image, just deleting some colours on it, not changing it's dimensions. It's coming from a sprite sheet of 11 images. All the images are blurred in the same way

Details

The camera is set orthographic.
The camera size is set to 95.
The camera is at [0,0,-10].
The background sprite is at [0,0,0].
The sprites are all at Z=0;
The sprite is W: 256, H: 174.
Anti-aliasing is disabled in the project.


texts: Run playing game in full-screen on one display, Unity IDE in another

texts:
I have multiple monitors (*). If the Unity (2018.1) IDE is open and maximized in one of them, is there an easy way to have it use one of the OTHER displays to run the game full-screen whenever I launch 'play' mode? Or alternatively, to undock the "Game" tab from the IDE & turn it into a normal window that can be moved to an adjacent display & maximized?

(*) If it matters, I'm running Windows 10, with the desktop extended across all three. The left and middle (main) displays are connected via DVI, the right display is my laptop (Dell Precision m4800 with Quadro K2100M). All three are 1920x1080.


texts: Updates for IOS AppStore Multiplayer Game

texts:
I am developing a multiplayer game for the web, android and ios. For the web and android i can instantly push out new versions of my game because they support executing remotly loaded code. But with IOS i need to wait for an Apple approval taking about 10 days. I want to push updates more then weekly.

What if my server code changes so the client MUST update? Run an old version of the server code just for IOS? How do other multiplayer devs handle this ?


texts: How can I create a game in RMVX without battle scenes?

texts: I want to create a story-like game which depends on situations based on your decisions. I don't want to have "battle scenes" in my game; can I disregard the EXP/HP stuffs to create my own game?


texts: Pre-existing voxel tools/libraries for Java

texts:
I want to do some development using voxel data as well as rendering it. My interest is more in the project its self, rather then things like working out rendering optimization techniques and working efficiently with large data sets, which I know have been done a billion times by other people.

However, all the existing libraries I can find seem to be for other languages. I have found PolyVox, which seems great, but I'd really much rather use Java for this.

Are there any fleshed out libraries? If not,I'm assuming I'm stuck using LWJGL and building something from scratch. Can anyone recommend some thorough tutorials on the subject?

Thanks so much.


texts:
I'm new to this. And I don't really understand 2D tile maps.

The tutorials I've read use arrays, but doesn't this get really difficult to manage when they get big?

And what if I want different floors, like going up/down stairs, do I need an array for every "level" of the game world?

Could anyone explain tile based maps as simple as possible please?
If you include code, please make it Javascript or pseudo code since it's all i know.


texts:
I'm using LibGDX, and I don't know where to start; I would like to deform a texture.

Let's say I have a PolygonSprite, and I have vertices and a texture.

Image 1 represents what I have. I would like to deform the texture, like in image 2, by changing the position of the vertices. I don't know how to do that, and I don't see the methods for this in the PolygonSprite class.

I don't want to re-create the vertices, I want to deform the texture based on the first set of created vertices. How do I do that?


texts: Duplicate packets and termination of packets in multiplayer game

texts:
I'm making a multiplayer game (lazertag) with real hardware.

After hours of research, I'm choosing the UDP instead of the TCP protocol to exchange data.

Because of how unreliable UDP is and because players want speed, I decided to have everything in the game that transmits data to transmit the same data more than once.

Due to my hardware limitations (AT89S52 microcontroller with HM-TRP radio modem set to 56kbps) and features I want in the game, I feel the maximum number of duplicate packets I should send out (along with the original) is 2 or 3 total.

Also, I have it setup where the receiver sets a flag if it receives an entire packet so it doesn't receive any more duplicate packets.

Currently, I have it where the server deliberately pauses between sending uninterrupted sets of duplicate packets. This pause indicates to the clients that a timeout occurred and that the next data that arrives is not part of the duplicate set.

Based on how I'm separating duplicate data, I find the method a bit slow because I have one global timer available to me. If I set the clock too small then the system basically freezes since there will be no time for other tasks to execute. Yes I'm literally time-slicing. If I set the clock too high, then the player could stall for a long time if he is disconnected from the network.

I thought of designating a special byte in the packet to indicate end of duplicate data but that probably won't work because chances are, that data won't be processed by the recipient (because he didn't receive it).

Is there any other way a player's hardware can efficiently know when duplicate packets are finished being sent instead of depending on a long timeout and letting the time run out?

Also, How many duplicate UDP packets would be necessary on a slowish connection (think high-speed dial-up internet) in order for the destination to receive at least one of the duplicates?


texts: Godot: How do I asign movement cost to tiles in a Tilemap?

texts:
Pathfinding

I am trying to apply godot's Navigation to create a pahtfinding enemy in a Platformer game. I've read about a method to allow for pathfinding to take into account gravity.

My issue is that what I know I must do is to add more movement cost to higher tiles.

How do I do this?

EDIT

I have since found the documentation for the Astar Node. Wish me luck.


texts: Alternative for using game object/prefabs for level generator

texts:
I just finished the Unity Tutorial for creating a simple 2D roguelike Mobile Game. Now I wanted to make my level bigger; finding or creating my own algorithm isn't the problem. My problem is that creating a game object or using a prefab for every single floor or wall tile is a bad idea. (Map 200x200 = 40000 objects). A comment under the tutorial said that and I'm incline to believe it. That much I can understand, but I can't find a alternative. What can I use besides object/prefabs?

Sidenote: I have decent programming skills, but am beginner with Unity.

The tutorial I followed: https://www.youtube.com/playlist?list=PLX2vGYjWbI0SKsNH5Rkpxvxr1dPE0Lw8F
I want to make the maps there bigger, but then everything goes slow motion.


texts:
so I am following a tutorial to make a snake game in my Xcode console. But the tutorial i am following is using windows and therefore the "system("clear")" command isn't working with my mac, and all of my research seems to show that there is no way to do that in Xcode

my question is, don't many games need to have their screen cleared constantly?
how would games that are being designed in Xcode clear their screens if there is no easy way to do this?