texts: I need to move a sprite from point A to point B. I have objX1, objY1, frames, and X2, Y2

texts:
I have a custom sprite class in Unity and I'm trying to make a method in where it moves from one point to another. Instead of using an Enumerator for time, I'm using real time game frames using static void methods inside of classes which inherit from a MainGame.cs script attached to the Main Camera, and this is called inside of MainGame's Update() method.

So what I have in the end are the following values:
SpriteID
OriginalX
OriginalY
MoveToX
MoveToY
CurrentFrames
TotalFrames

I'm not asking anyone to do the work for me, just that if there's a place I could be directed to in where I could find the math necessary to solve the problem that'd be a huge help. I'm not using any vectors here, just the raw math using only those variables. I don't know if someone has found an answer for calculating it based on update frames...

public class Sprite : MainGame {

public static int State = 0;
public static int CurrentFrames = 0;
public static int TotalFrames = 0;

 public static void Move(int SpriteID, int OriginalX, int OriginalY, int MoveToX, int MoveToY, int TotalFrames)
 {
    switch (State) {
    //init
       case 0:
       CurrentFrames = 0;

       State = 1;

       break;

       //run
       case 1:
       if (CurrentFrames < TotalFrames) {
       //do math here

          CurrentFrames++;
       }

       if (CurrentFrames >= TotalFrames) {
          State = 2;
       }
       break;

       //end
       case 2:
          //Reset values here
          //Shut off
          State = 3;
       break;
    }
 }
}

EDIT 10212016 456PM: What I've figured out so far, now...

if (CurrentFrames < TotalFrames) {
    DistanceX = MoveToX - OrigX;
    MoveForwardXFloat = (float)DistanceX / (float)Frames;
    OrigX += (int)MoveForwardXFloat;
}


texts: Rotate a 3D object in Unity3D on button click

texts: There is a 3D character in my application developed using Unity3D.  Now I want to rotate this 3D character when the user press the rotation button. I tried several ways, but didn't work. How can I rotate a character when the player presses the rotation button?


texts: implementing different users in XNA - XML

texts:
So I am making a simple 2D game in XNA, and I want to implement different users (players), so each person playing can have their own high score, can only play levels they've already played, can only edit levels they've made, etc.

The levels are currently stored in XML, in the format:

  <level>
    <name>Level Name</name>
    <number>14</number>
    <authorTime>12.45</authorTime>
    <map>...</map>
  </level>

I was wondering what would be the most efficient way, and the best practise approach, to implementing this?

I am currently torn between two options: 1. each level having a <users> tag, containing a user ID and a time if they have completed the level. 2. Having a separate XML file, containing users and a list of their levels and times.

Are these good ways to do this? Are there other ways to do this better?

Thanks,

Simon


texts: How to move my cube left or right using touch Inputs (C#) in unity

texts:
I am trying to create a 3d game in unity. I have a cube in unity and I want it to move left or right on swipe . It should move to a distance till where user swipe or take their finger off of a screen. I want it to move fast or the cube should move fast on swipe and cube should flow smooth. Like in the gif there is a circle and the user use their finger to move the circle till wherever the user swipe it and it should be instant and I want my cube to move like that at a distance till where user swipe their finger and it should be instant and fast.
 I don't know how to do it. Any help is appreciated!


texts:
I'm making a topdown 2D RPG in Unity.
All moveable objects have Rigidbody2D-components with gravity set to 0, linear drag set to 5 and different masses.
Walls are stationary boxes with BoxCollider2Ds.

Here's my problem:
http://a.pomf.se/nifmcn.webm
The rock is not particularly easy to see, but if you watch when I'm trying to walk into a wall, the player kind of jags in and out of the wall.

Of course, this is because I'm moving the player by moving it's Rigidbody2D, for example:

rigidbody2D.transform.position += Vector3.up*Time.deltaTime*speed;

The box then throws the player in the opposite direction of what he was going.

What's a good way of stopping a player from moving in the direction he's trying to go?
More specifically, how do you detect which way he's going? Do you find the angle between the player and the object/wall?

This is kind of an open question, but I think it's extremely important.


texts: OrthographicCamera and viewport not giving expected effect

texts:
I recently asked a question about this area that I think was too broad, so I will try a new approach.

I have the following code I am experimenting with:

        batch = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("bg_test.png"));

        sprite = new Sprite(texture);
        sprite.setSize(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT);

        myGameWidth = Gdx.graphics.getWidth();
        myGameHeight = Gdx.graphics.getHeight();

        float aspectRatio = (float)myGameHeight / (float) myGameWidth;

        cam = new OrthographicCamera();
        viewport = new StretchViewport(GAME_WORLD_WIDTH * aspectRatio, GAME_WORLD_HEIGHT * aspectRatio, cam);
        viewport.apply();
        cam.position.set(GAME_WORLD_WIDTH / 2, GAME_WORLD_HEIGHT / 2, 0);

Now I thought StretchViewport was supposed to stretch the image across whatever screen you tried, however I get this result in desktop when I try with config.height=800, config.width=400:

Now if I change the following line:

viewport = new StretchViewport(GAME_WORLD_WIDTH * aspectRatio, GAME_WORLD_HEIGHT * aspectRatio, cam);

to:

viewport = new StretchViewport(GAME_WORLD_WIDTH, GAME_WORLD_HEIGHT, cam);

(I remove aspect ratio) This makes the image fill the screen the way I thought StretchViewport should, but I dont want to ignore the aspect ratio.

What makes it even weirder is that this only happens when I run desktop heigt>width(portrait), if I change it to the opposite width>height(landscape) then the image fills the screen too much, so the edges of the image go outside the screen :S

Am I missing something here? Is my aspectRatio wrong? I want to make sure my games will scale nicely across devices before I really get started with libgdx, right now all different viewports show me the same result with this padding.

I really can't figure this out, I get the behaviour (stretch) I want when I dont use aspectratio, but everywhere I read it tells me to use aspectratio. I really just wanna solve this so I can start with the fun stuff  ^^


texts: How to fade in and out a game object with two child game objects

texts:
I have been fading game objects in and out using the following code. Now I want to fade out a game object with two child game objects. How can I do this?

    IEnumerator FadeToForGO(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) {

    // Cache the current color of the material, and its initiql opacity.
    Color color = material.color;
    float startOpacity = color.a;

    // Track how many seconds we've been fading.
    float t = 0;
    if (isEnabled) {
        gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;

    }

    while(t < duration) {
        // Step the fade forward one frame.
        t += Time.deltaTime;
        // Turn the time into an interpolation factor between 0 and 1.
        float blend = Mathf.Clamp01(t / duration);

        // Blend to the corresponding opacity between start & target.
        color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);

        // Apply the resulting color to the material.
        material.color = color;

        // Wait one frame, and repeat.
        yield return null;

    }

    if (!isEnabled) {
        gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;

    }

}


texts: How to achieve highly accurate car physics such as Liveforspeed?

texts:
Liveforspeed is a racing simulator, there is amazing amount of realistic physics. for example, tires get warm, tire actually deforms when you turn corners. You need to play this game with a mouse at the minimum because it almost drives like the real thing.

Anyhow, how does one achieve that level of physics simulation? Are there off-the-shelf solutions out there? If not, how does one start with simulating real world physics as close as possible.

I would love to be able to work on an opensource car physics focused game. Imagine, more passionate developers, it could keep things going.


texts:
I want to add 1 to directions every time the shift key is pressed. Since I need to check the key press, I have to do it in Update, but in Update this code is executed multiple times and the directions goes all the way up to 4 before going back to 1.
How do I make it so that every time the shift key is pressed, directions is added by 1 and only 1? Thanks in advance. :)
private int directions = 1;

var keyboard = Keyboard.current;

if (keyboard.shiftKey.isPressed)
        {
            directions++;

            if (directions == 5)
            {
                directions = 1;
            }

        }


texts:
What is the best approach to let a Phaser.Sprite do discrete movements?

It should continue moving along all possible values, but at the end of a move it must end up on a certain position which will have the following property: position.x % SOME_FIXED_VALUE = 0 and position.y % SOME_FIXED_VALUE = 0


texts: I'm rotating an object on two axes, so why does it keep twisting around the third axis?

texts:
I see questions come up quite often that have this underlying issue, but they're all caught up in the particulars of a given feature or tool. Here's an attempt to create a canonical answer we can refer users to when this comes up - with lots of animated examples! :)

Let's say we're making a first-person camera. The basic idea is it should yaw to look left & right, and pitch to look up & down. So we write a bit of code like this (using Unity as an example):

void Update() {
    float speed = lookSpeed * Time.deltaTime;

    // Yaw around the y axis using the player's horizontal input.
    transform.Rotate(0f, Input.GetAxis("Horizontal") * speed, 0f);

    // Pitch around the x axis using the player's vertical input.
    transform.Rotate(-Input.GetAxis("Vertical") * speed,  0f, 0f);
}

or maybe

// Construct a quaternion or a matrix representing incremental camera rotation.
Quaternion rotation = Quaternion.Euler(
                        -Input.GetAxis("Vertical") * speed,
                         Input.GetAxis("Horizontal") * speed,
                         0);

// Fold this change into the camera's current rotation.
transform.rotation *= rotation;

And it mostly works, but over time the view starts to get crooked. The camera seems to be turning on its roll axis (z) even though we only told it to rotate on the x and y!

This can also happen if we're trying to manipulate an object in front of the camera - say it's a globe we want to turn to look around:

The same problem - after a while the North pole starts to wander away to the left or right. We're giving input on two axes but we're getting this confusing rotation on a third. And it happens whether we apply all our rotations around the object's local axes or the world's global axes.

In many engines you'll also see this in the inspector - rotate the object in the world, and suddenly numbers change on an axis we didn't even touch!

So, is this an engine bug? How do we tell the program we don't want it adding extra rotation?

Does it have something to do with Euler angles? Should I use Quaternions or Rotation Matrices or Basis Vectors instead?


texts: Is it possible to use an SVG as a texture for a 3d object?

texts:
I'm using the Vector Graphics plugin for Unity 2019 and am able to drag an SVG into the scene. However, I am not able to drag it onto a 3d object as I am with a PNG. My goal is to make 3d cubes that rotate with a particular icon on each side of the cube.

I came across this related post: SVG textures for 3D game objects in Unity? but I'd like to make sure there haven't been any advancements since 2017 in this area. Also, would it be possible to add an SVG to a material? I can't figure out a way to do it but I am not very experienced with Unity.


texts: How can I architecture the cards and boards of this board game?

texts:
I want to create a board game (at least it's structure and engine, not the graphics), and since It's the first time I do this I don't know where to start.

It's a turn based strategy card game where cards that act differently, some are placed and moved on the board, some are placed but don't move, and some are played from the hand but not placed on the board.

Well, I don't know how to translate this to code. I thought that I should have a interface for the Cards, but since there are various types of cards that act very differently it doesn't make sense . Then I thought that there should be a class for each Player which stores which of his cards are played, which are left etc.. Something like this:

public Class Player
{
 private List<Card> PlayableCards;
 private List<Card> OutOfGameCards;
}

But there's a fixed amount of cards of each type, so its useless to have a List<T> (besides as I said I don't think I'll have a Card class).
Then How should I approach this? Having the cards as individual variables? It doesn't sound right.

The next thing is the Board, it's formed by 8x8 squares where the cards are placed. How do I identify each placed card with a card in the code?

Maybe something like this:

public Class GameBoard
{
 private Square[][] SquareGrid;
}

If I do it this way its easy to separate each square and access it by it's position (SquareGrid[3][4]=3x4). But do I store which card is in each Square? Or do I store in which square is each card? After that there's a "special zone" outside this board and everything gets more messy.


texts: Python collision left works, but not right

texts:
I am continuing to work on collision detection. It appears for the most part, everything I have implemented is working. When the game starts, the character is on the left side of the screen (plus a few pixels). If I hold down the left key so he is pushed against the wall, he doesn't go anywhere like is supposed to happen.

However, when I move the character to the right up to the first ledge something weird happens:

At first, he doesn't go through the ledge like he's supposed to:

But then, after holding down the right key for a while, he starts to creep into the ledge:

If I hold down the right key long enough, he ends up inside the ledge completely:

(can't post another pic, because I don't have enough rep)

There is no rhyme or reason as to how long it takes for him to creep forward. It seems to happen at random intervals.

Any clues as to what is happening? The weirdest thing to me is that it only happens when he is colliding with the left side of a "wall" and not the right side. I held down the left key on the left side of the map (the beginning) for quite a while and nothing happened, again like is supposed to happen.

Relevant code:

def col_ground(self, sprite, wall):
    return self.walls[wall].collidepoint(sprite.feet.midbottom)

def col_left(self, sprite, wall):
    return self.walls[wall].collidepoint(sprite.feet.midleft)

def col_right(self, sprite, wall):
    return self.walls[wall].collidepoint(sprite.feet.midright)

def update(self, dt):
    """ Tasks that occur over time should be handled here
    """
    self.group.update(dt)
    # sprite must have a rect called feet, and move_back method,
    # otherwise this will fail

    # TODO: this could probably be modified to handle anytime
    # the sprite is just on the ground or hitting a corner instead
    # of having seprate instances of where the sprite hits the right
    # or left side of a wall
    for sprite in self.group.sprites():
        wall_collide = sprite.feet.collidelist(self.walls)
        walls = sprite.feet.collidelistall(self.walls)

        if wall_collide > -1:
            # if the sprite hits the ground
            if self.col_ground(sprite, wall_collide):
                self.hero.jumping = False
                sprite.move_back_y(dt)
            # if the sprite's right side hits a wall
            if self.col_left(sprite, wall_collide):
                sprite.move_back_x(dt)
            # if the sprite's left side hits a wall
            if self.col_right(sprite, wall_collide):
                sprite.move_back_x(dt)
            # if the sprite is in a corner
            if len(walls) == 2:
                # if in a corner, keep him from going up or down (x, y)
                if not self.walls[walls[1]].collidepoint(sprite.feet.topleft) and \
                not self.walls[walls[0]].collidepoint(sprite.feet.topleft):
                    sprite.move_back_x(dt)
                if not self.walls[walls[0]].collidepoint(sprite.feet.topright) and \
                not self.walls[walls[1]].collidepoint(sprite.feet.topright):
                    sprite.move_back(dt)

If you need any more code snippets or explanation, please let me know.

Edit (movement functions):

def move_back_x(self, dt):
    """ If called after an update, the sprite can move back
    in the x
    """
    self._position[0] = self._old_position[0]
    self.rect.topleft = self._position
    self.feet.midbottom = self.rect.midbottom

def move_back_y(self, dt):
    """ If called after an update, the sprite can move back
    in the y direction
    """
    self._position[1] = self._old_position[1]
    self.rect.topleft = self._position
    self.feet.midbottom = self.rect.midbottom

def move_back(self, dt):
    """ If called after an update, the sprite can move back
    """
    self._position = self._old_position
    self.rect.topleft = self._position
    self.feet.midbottom = self.rect.midbottom


texts: I added a terrain in Unity, but can't see it

texts:
In Unity I added a terrain through Create → 3D Object → Terrain. It didn't show up and I can't see it. I tried to press F to focus on it, but I still don't see it. What am I doing wrong?

Here is a screenshot:


texts:
I am trying to rotate a direction vector (0,0,1,0) by a rotation quaternion in DirectX.

From what understanding, to rotate the vector you must do

NewVector = rotQuaternion * Vector * inverse(rotQuaternion)

In directX11, I am testing out the algorithm above using an identity quaternion.

XMVECTOR qIdentity = XMQuaternionIdentity();
XMVECTOR inverse = XMQuaternionInverse(qIdentity);
XMVECTOR test = qIdentity * XMVectorSet(0.0f,0.0f,1.0f,0.0f) * inverse;

My new test vector should just be (0,0,1,0), however it is completely zeroed out, and I am not exactly sure why or if I multiplied it correctly.


texts:
Basically I want to setup UnityIAP for implementation of weekly or monthly subscription for apple store game. I completely read following article given by Unity:

Integrating Unity IAP In Your Game

After this I become aware with actual implementation but i have following questions arise:

how we can get information about subscription already purchased by this user?
how we track time for auto renewable subscription purchase?

Please give me some information about this.


texts: How do I stop a looping music file from playing in crafty.js? I want the music to stop playing once a gameover condition has been reached.


texts: Making a dialog that expands to fit its text

texts:
I'm trying to make an OK/Cancel-style dialog which will expand to fit its text in Unity 5.6. I've been trying to pull this off using Unity's built-in UI layout components, but so far I haven't been able to get it exactly right.

The dialog has a background, a title, a body, and two buttons. The goal is for the dialog to resize itself vertically to fit the length of the text. Here is an example with placeholder graphics:

I have this almost working properly, but I created it by abusing the built-in layout components and it doesn't always behave properly. Here's how it's currently set up:

Background is an Image

Vertical Layout Group:

Control Child Size: Width

Content Size Fitter:

Horizontal Fit: Unconstrained
Vertical Fit: Min Size

Background has the following children:

Title is a Text
Body is a Text

Content Size Fitter

Horizontal Fit: Unconstrained
Vertical Fit: Preferred Size

Buttons is a GameObject

Horizontal Layout Group

Child Force Expand: Width and Height

This setup works about 90% of the time, with the dialog properly resizing according to the text. However, at certain (seemingly arbitrary) body lengths, an extra blank line will be added to the Body text, which disrupts the vertical spacing and gives the dialog a strange look:

This isn't too surprising, because you're not supposed to put a Content Size Fitter on a child of a Layout Group; however, I couldn't figure out any other way to get the dialog to vertically expand to fit more text. Is there a better way to handle this?


texts: Is C# viable for a real-time game server?

texts:
Most of the question is in the title.

Basically, I'm starting to develop a 2D multiplayer action game. The client is (probably) going to be in XNA, and I thought I'd ask here about whether it's a good idea to use C# for server side development as well.

I guess the fact that the language is managed is not something problematic as Java is being used in even MMO game servers (correct me if I'm wrong), so are there any reasons to avoid C# for this purpose? I need it to be fast and responsive, to communicate over TCP, to chat with an SQL server. And if there is no reason to avoid C#, how would I deploy such a web server, would it be a .NET EXE running on the server machine?


texts: Lua Unknown error when typing something in Zerobrane studio IDE

texts:
What is this weird error that I am getting when I typing something in the Zerobrane studio IDE? It crashes my IDE. But The game project compiles and runs fine.

When I turn off "Autocomplete Identifiers" from Edit menu, then the error doesn't come up.

Also, I searched entire google and facebook for some help or solution but no luck at all.


texts: Good way to play a sound when something happens? How does this sound?

texts:
So I was thinking about how monolithic my classes get a lot of the time. For example, in the Character class's Jump method, one may have a reference to a sound effect object and play that. By itself that is fine but when physics, animation, collision, etc. are taken into account, the Jump method gets huge and the Character class has a lot of dependencies to many different things. Still, this may be fine. However, what if we no longer want a sound to play when the character jumps? Now, we have to find that specific line of code in the jumbled mess of the Jump code and comment it out or whatever.

So.. I was thinking..

What if, instead, there was some sort of AudioSystem class and all it did was subscribe to random events it's interested in in other classes. For example, the Character class may have a Jumped event (static too, I suppose) that is raised within the Character class in the method. Then, the Character class would know nothing about the little sound effect that is played when the character jumps. The AudioSystem would just be a huge class that the programmer could retreat to to hook up sound effects with certain events that happen in the game through the use of static events. Then, if it got too big it could be separated in to subclasses like EffectsAudioSystem, BackgroundAudioSystem, AmbientAudioSystem, et cetera.

Then, in the options for the game, one could have a checkbox to enable or disable these sorts of sounds and all that would need to be done is just to disable that one system with a simple and single Boolean flag. This idea of systems could also be extended in to things like physics, animations, etc. to the point where most of the game responses resulting from player actions are hooked up through these elaborate and decoupled systems.

Okay, so my question may be a little vague, but how does this sort of thing sound? I haven't really ever heard of much kind of talk about this sort of system. This is all up in my head right now without any coding done so far so perhaps it's one of those "good in theory but not in practice" kind of deals. Would this kind of system work with a larger game or would it eventually break down and become even more of a spaghetti mess than the original system?


texts: OpenGL vs OGRE : Which is the best for beginner?

texts:
I am interested in getting into game development and posses good C/C++ programming skills. I have tried OGRE before, and I am curious whether I should learn either OGRE or OpenGL as a starting point.

From my understanding, OGRE is a wrapper for OpenGL and DirectX. So, supposed that I learn OGRE, do I still need to learn OpenGL as well to develop a game?

Also, can someone points me good tutorial for OpenGL? I found that OGRE is well documented (it's even come with the distribution!) but for OpenGL, most of the tutorials I came over are outdated.


texts: Why does Unity editor freeze up if left unfocused for a while?

texts:
If Unity editor loses focus for too long (such as because I'm tabbed out into my browser or Blender), then I find that it needs about 15-30 seconds until I can interact with it again when it gets focus again. It seems like it is paused.

Is this a bug or my fault?


texts: Fixed timestep with interpolation & rounding draw positions: jerky animation when the character is not moving

texts:
I've implemented a deterministic, fixed timestep system from here:
http://gafferongames.com/game-physics/fix-your-timestep/

Everything works fine, output is the same with each step but there's one problem - the animation is jerky while the character isn't moving.

Here's the code responsible for interpolation:

    draw.x = previous.getX() * alpha + current.getX() * (1.0f - alpha);
    draw.y = previous.getY() * alpha + current.getY() * (1.0f - alpha);

    g2d.drawImage(image, (int)draw.x, (int) draw.y, null);

Here's how 'alpha' looks like:

0.29991353
0.35988057
0.41996205
0.41996205
0.4799291
0.4799291
0.53989613
0.5998632
0.5998632
0.65994465
0.7199117
0.97999954
0.039999668
0.099999785
0.1599999
0.21999958
0.2799997
0.33999982
0.39999995
0.4599996
0.51999974

Let's assume that player's initial position is x = 100 and he's not moving.

His interpolation gives values like 100.0000123123 (which when casted to int gives 100 - OK) but it also gives values like 99.99999998, which when casted to int gives 99 (which makes the jerk).

I don't know how to handle this, maybe just make a statement (if previous != current then do interpolation) and that's it?

Thanks very much

Edit
Here's my gameloop:

    float fps = 60;
    float dt = 1 / fps;
    float accumulator = 0;

    Time time = new Time();
    float frameStart = time.getSeconds(); - // returns seconds since initialization for ex. 1.32234, 6.43243

    while(match_running) {

        float currentTime = time.getSeconds();

        accumulator += currentTime - frameStart;

        frameStart = currentTime;

        if (accumulator > 0.2f)
            accumulator = 0.2f;

        while (accumulator > dt) {
            doPhysics(dt);
            accumulator -= dt;
        }

        float alpha = accumulator / dt;
        gamePanel.drawGame(alpha); // here's the interpolation

    }


texts: Rule based procedural terrain generation

texts:
How one generates procedural terrain is pretty straight forward. But once you setup your terrain you don't really have a fine level of control where which details will go.

One solution I can think of is to store rules as functions, i.e. Square, circle, etc., which will override rules in the area. For example, in mountains terrain we could place a function which will make them flat or terraced.

What I have trouble figuring out is how to store those functions (assuming terrains can be in principle infinite or at least planetary scale). Should they be placed within existing coordinate system, or stored locally to terrain ?

I seen something like that done in Star Wars Galaxies, but it's really hard to find any details about implementation of system.


texts: How can I get rid of the diagonal wires in wireframe boxes?

texts:
I create a box with a material and set that material to be wire framed.

Box b1 = new Box(new Vector3f(1.0f, -2.0f, 1.0f), 1.0f, 1.0f, 1.0f);
Geometry geom1 = new Geometry("Box", b1);
Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat1.getAdditionalRenderState().setWireframe(true);
mat1.setColor("Color", ColorRGBA.Blue);
geom1.setMaterial(mat1);

However, because the box is drawn using triangles there are diagonal wires visible:

How can I get rid of these diagonal wires (not draw them)?


texts:
I'm currently working on a WebGL project to realise an idea I've had for some years. On my desk is book on making a space sim written 15 years ago.

There I found some algorithm for particles in space. The idea is simple: A cloud of particles that stay in place so they fly past the player, but reset to be in front of the player when they move past the ship. This shows the player they're moving while there's nothing else around. For this, I reworked the algorithm found in the book a little:

ParticleField.prototype.updateCloud = function(frustum, position, direction) {
  var s = this.size, s2 = s * 2;

  for (var i = 0; i < this.vertices.length; i++) {
    if (!frustum.containsPoint(this.vertices[i])) {
      this.vertices[i].set(
        (position.x + s - Math.floor(Math.random() * s2)) + (s * direction.x),
        (position.y + s - Math.floor(Math.random() * s2)) + (s * direction.y),
        (position.z + s - Math.floor(Math.random() * s2)) +
                         ((s + Math.floor(Math.random() * s2)) * direction.z)
      );
    }
  }
};

Where s is the size of cloud. I played around with the sizes, but this simple function has several weaknesses.

The particles 'pop up' in front of the player when they're moving.
If the player backs up and moves backwards, the particles won't reset, leaving the cloud visible popping the illusion.
Particles appear to be flying through the player.

Without regard of how the particles look (they're simple points right now), how can I make this look more natural? I've seen the effect in games like Elite: Dangerous and Freelancer, and I'd like to be closer to them, and I'd appreciate any hint on the topic.


texts:
Possible Duplicate:
  Can you access Kinect motion sensing from XNA?

bunch of questions:

Is it possible for me to create a Kinect application using XNA and deploy it to Xbox360 platform?
What should I use, will Kinect SDK for Windows be okay for this task?
What about licenses, is it free to use or should I pay for licenses?

Thanks for any answer or url...


texts:
I'm quite experimented in objective C, but now i'm tried cocos2D and his features.

I need to add a body on a spritesheet (if possible on a classic 'UIImageView'), in order to detect collisions after.

Is there a way to create a box2D body, and that it suits sprite position ?

Because i wrote :

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    CGPoint current = myUIImageView.center;
    int accelerator = 25;
    if (current.y > 70 && current.y < 407)
    {
        current.y -= acceleration.y*accelerator;
    }
    else if (current.y <= 70)
    {
        if (acceleration.y < 0)
        {
            current.y -= acceleration.y*accelerator;
        }
    }
    else if (current.y >= 407)
    {
        if (acceleration.y > 0)
        {
            current.y -= acceleration.y*accelerator;
        }
    }
    myUIImageView.center = current;
}

and found some codes, but looks very hard...

Thanks for your help !


texts:
I'm trying to load sound into my game. I downloaded an .mp3 sound (a second long) and tried to load it both as Song and as SoundEffect, but it didn't work, so I tried loading the same sound but as .wav and I was able to load it as a SoundEffect. The problem is that the sound that is coming out sounds like static noise. I looked a bit into this and found out I need to load sounds as .xnb files, so I downloaded 'XNAContentCompiler' project and tried to compile the sounds causing a 'PInvokeStackImbalance' error.

So I found this thread: http://xboxforums.create.msdn.com/forums/p/65519/65519.aspx

Saying I can ignore this and continue.

The xnb file fails to be created when I try to convert the .wav files, saying it is 24-bit audio and I may only use 8 to 16 bit. So I tried to compile the .mp3 file and it succeed, creating a 1k file that I still cannot load not as a Song and not as SoundEffect.

I'm now completely lost on this and can no longer understand what I need to try to load and what is a different problem completely, and I would love some explanations.


texts: How I randomise a list of audio clips in Unity and remove it from the list once the clip is finished?

texts:
I have 4 audio clips. When I play a press a certain button in Unity, the data is sent to MAX/MSP and the audio is played. I created a list a signals (As shown below in the code). What I want is that, the signal list is randomised. The user presses a button to listen to the audio (which works fine). Once the clip is finished the user presses Next Trial button. Once the Next Trial is pressed. The previous clip is removed from the list. Once all the clips are finished. A message is displayed in the Debug.Log("All trials finished"). I have the following problems:

One of the audio clips is repeated again. It appears that the audio clips are not removed from the list.

How do I write the audioclip index to a csv file?

Code:
public class SignalToMax : MonoBehaviour { private static int localPort; private string IP; // define in init public int port = 8050; // define in init

 // "connection" things
 IPEndPoint remoteEndPoint;
 UdpClient client;
 // experiment case
 public string experimentCase = "A";
 string strMessage = "";
 public List<int> signals;
 public static int stimIndex;
}

void Start() {

NextTrial = GameObject.FindGameObjectWithTag("NextTrial").GetComponent();

     signals = new List<int> { 1, 2, 3, 4 };
     // define
     IP = "127.0.0.1";
     port = 8050;
     // ----------------------------
     // Senden
     // ----------------------------
     remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
     client = new UdpClient();
     NextTrial.onClick.AddListener(Advance_Trial);
}

void Advance_Trial() {

     int signalIndex = Random.Range(0, signals.Count);
     int currentSignal = signals[signalIndex];
     stimIndex = currentSignal;
     signals.RemoveAt(signalIndex);
     string text = signalIndex.ToString();
     byte[] data5 = Encoding.ASCII.GetBytes(text);
     client.Send(data5, data5.Length, remoteEndPoint);
     Debug.Log("<color=magenta>Current source signal is:</color>" + currentSignal);

     if (signals.Count > 0)
     {
         Debug.Log("<color=blue>Signal count before removal was:</color>" + signals.Count);
         Debug.Log("<color=yellow>Source signal removed</color>");
     }
     else
     {
         Debug.Log("<color=green>All Trials finished</color>");
     }
 }


texts: Find the 4 Corners of a Bounding Box of a Rotated, Offsetted Square

texts:
How does one find the coordinates of the 4 corners of a bounding box of a square of width w and height h that is rotated theta degrees and is offset from the origin x in the x direction and y in the y direction?

Here is a visual example of what I mean:

Here is some python3 code that I came up with, but it only works in the right quadrants except when theta = 0 or 360 or etc.:

import math

def bounds(x,y,w,h,theta):
   theta = theta * math.pi / 180

   A = ( x, y+round((math.sin(theta)*w), 2) )
   B = ( x+round((w/math.sin(theta)), 2), y+round((math.sin(theta)*w), 2) )
   C = ( x+round((w/math.sin(theta)), 2), y+round((math.cos(theta)*h), 2) )
   D = ( x, y+round((math.cos(theta)*h), 2) )
   print(A)
   print(B)
   print(C)
   print(D)

I was reading this but I could not figure it out for my specific problem.

Any help is much appreciated. Next time I will use matrices to store all the transformation data because this would be so much easier that way.


texts: How does "Additional Design" or "Additional Programming" differ from just "Design" or "Programming?"

texts: In the credits of video games there are often separate headings for "Additional Programming", "Additional Design" or "Additional Art"- often containing the names of people who work in other departments. What is the need for this separation and how do "Additional" developers differ from the "regular" ones. Does this imply that people from other departments do design/programming/animation as well?


texts: Havok Physics : "hkQuaternionf not normalized/invalid!" when hkpWorld::stepMultithreaded()

texts:
today I want to ask a question about Havok Physics 2012.

My havok version is 2014.1.0-r1 (x86 SIMD version), and I'm using Visual Studio 2012 on Windows 8.

My problem is, that once I add a rigid body to the world, the next time I call hkpWorld::stepMultithreaded(), it breaks in some SSE math related function and gives me this error message through my error report function.

  C:\NightlyJobs\09-07-Sun-01\Source\Common/Base/Math/Vector/Sse/hkSseVector4Util.
  inl(307): [0x1FF88F0E] Assert: hkQuaternionf not normalized/invalid!

Here's the stack trace:

  (null)(0):'hkDefaultError::message'
  (null)(0):'hkError::messageAssert'
  (null)(0):'hkVector4UtilImpl::convertQuaternionToRotation'
  (null)(0):'hkRotationf::set'
  (null)(0):'hkTransformf::setRotation'
  (null)(0):'hkSweptTransformUtil::calcTransAtT1'
  (null)(0):'hkSweptTransformUtil::_stepMotionState'
  (null)(0):'hkRigidMotionUtilApplyForcesAndStep'
  (null)(0):'integrateJob'
  (null)(0):'hkpMultiThreadedSimulation::processNextJob'
  (null)(0):'hkJobQueue::processAllJobs'
  (null)(0):'hkpWorld::stepMultithreaded'

Here's how I create and add the rigid body.
It's so basic that I didn't think there would be any room for bizarre error in it...

hkpSphereShape* sphere = new hkpSphereShape(radius);  // radius is 10.0f here.

hkpRigidBodyCinfo rigidBodyInfo;
rigidBodyInfo.m_shape = sphere;

m_RigidBody = new hkpRigidBody(rigidBodyInfo);

world->markForWrite();
world->addEntity(m_RigidBody);
world->unmarkForWrite();
m_RigidBody->removeReference();

I don't set position or rotation of the rigid body myself, so why it breaks in some quaternion related function is beyond me.

I speculated it might be one of those multithreading-related bizarre errors, so I tried changing

m_WorldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_MULTITHREADED;

to

m_WorldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_DISCRETE;

and

m_World->stepMultithreaded(m_JobQueue, m_CpuThreadPool, timeStep);

to

m_World->stepDeltaTime(timeStep);

but the problem persisted.

Do you know something that I could be doing wrong ?
Please tell me in the comments if you need to see some of my other code to help!
Any help would be greatly appreciated, thanks!


texts:
I want to scale an image before screen resume in AndEngine so I have applied the following code to my sprite:

ScaleModifier scaleDrag1 = new ScaleModifier(1, 1, 0.7f);

drag1.registerEntityModifier(scaleDrag1);

But my issue is that the scaled image is shown when the screen resumes because of the 1 duration. It makes my sprite scale after the screen resume so the scaling is visible to the user, I tried setting the duration to 0 but then that sprite is not shown.

Can anyone tell me what should I do to scale image before resume in AndEngine.


texts: Best method for 2 layer tile based map scrolling

texts:
What is the best general approach to implement scrolling for a 2D tile based game?

I need to scroll the map with a constant speed, lets say 2 pixels every frame (like in a top down shooter).

The tiles are 32x32 and the map is quite big, lets say 10 x 300.

There are 2 layers:
- first is the background layer
- second is the forgeground layer with obstacles and enemies

The target plattform is android and I want to use OpenGl.

What is best practice?

a) Draw only the visible Screen all the time (every frame)
b) Load complete map into memory and just move the camera

Is there a difference in performance and determining collision etc.?

Thanks for any help!


texts: C++ Passing Functions to Objects/Projectile system woes

texts:
I am new to C++ development and I am trying to create a more flexible projectile system.

In my current system I apply a equation to move the point down the bullet path.

class Bullet{
    public:
      float x;
      float y;
      float speed;
      float angle;

     void Update(){
     x=(speed*cos(angle)) + x;
     y=(speed*sin(angle)) + y;
     };
}

This works fine for moving a bullet on an angle, however I would like to generate much more complex paths, without over complicating the bullet class.

My idea was to pass a function to the bullet class that would be used to move the object but I have not found any way to do this.

Example of what I want to do:

class Bullet{
    public:
      function dostuff();
      float x;
      float y;
      float angle;

     void Update(){
     dostuff(x,y,angle,speed);
     };
};

class Enemy{
    public:
      float x;
      float y;
      float speed;
      float angle;

     void shoot(){
      Bullet bullet;

      auto movangle = [](float x, float y, float angle,float speed)
      {
         x=(speed*cos(angle)) + x;
         y=(speed*sin(angle)) + y;
      };
      bullet.dostuff = movangle;
      bullet.Update();
     };
};

If anyone knows of any ways to implement a system like this, or ideas on alternatives that could produce similar results It would be appreciated as I am somewhat stumped.


texts: Issues upscaling pixel art with SampleState.PointClamp

texts:
I'm developing a 2D game, and I'm striving to create a nice blocky low-res appearance for the game, yet allow it to be played at variable resolutions. So, I've researched resolution independency and have a nice system in place to have my game rendered at 640x480 to a RenderTarget2D, and then have the RenderTarget blown up on the back buffer. Anybody that's looked into this knows that by default scaled images will be antialiased, and to disable that, change the SampleState to PointClamp. So, I've done that, but now I'm having this issue where my sprites aren't upscaling properly. Certain pixels are becoming particularly chunky where they shouldn't be, and I'm not sure what the cause of this behavior is, and I haven't been able to find any documentation of anybody else having this issue, can anybody offer any insight?

The last image illustrates the image rendered in game at 2X the original size. A 2:1 ratio should be a pretty straightforward scale to render, but if you look closely, there are some pixels that are at half size the others.

Edit #2: Here's some code regarding the scaling.

First, the game is captured by the render target at 640x480 resolution, then it is drawn at the back buffer's resolution (in the second image, reslution is 800x600, in the third image, resolution is 1280x960, I haven't messed with alternate aspect ratios yet).

graphicsDevice.SetRenderTarget(RenderTarget);
spriteBatch.Begin();
spriteBatch.Draw(Texture,
            new Rectangle((int)location.X, (int)location.Y, frameWidth, frameHeight),
            new Rectangle((int)spriteLocation.X, (int)spriteLocation.Y, spriteWidth, spriteHeight,
            Color.White,
            0f,
            Vector2.Zero,
            effect,
            .826f);
spriteBatch.End();
graphicsDevice.SetRenderTarget(null);
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null);
spriteBatch.Draw(RenderTarget, new Rectangle(0,0, backbufferWidth, backbufferHeight), Color.White);
spriteBatch.End();

Edit #3: Code involving the sprite's height and width.
First, in the class that my monster inherits from, is this little method that runs in the base class' Update() method. It just makes sure that if I have animations with non-uniform sizes, that the sizes are updating properly.

protected void UpdateFrameSizes()
    {
        frameWidth = animations[currentAnimation].Frames[animations[currentAnimation].currentFrame].SizeAndsource.Width;
        frameHeight = animations[currentAnimation].Frames[animations[currentAnimation].currentFrame].SizeAndsource.Height;
    }

Then, just to make sure that the Width and Height were correct in his animation class, I checked those:

idleFrame1 = new AnimationFrame(Texture, new Rectangle(154 * 0, 107 * 0, 154, 107), 1f);
        idleFrame2 = new AnimationFrame(Texture, new Rectangle(154 * 1, 107 * 0, 154, 107), 1f);
        idleFrame3 = new AnimationFrame(Texture, new Rectangle(154 * 2, 107 * 0, 154, 107), 1f);

All looks correct here, I even went to the source image and counted the pixels (Yes, I know, his sprite sheet's dimensions are weird, but they're accurate).

And then this data is all used in Edit #2's code snippet during the draw method.


texts: Calculating rotation matrix for an object relative to a planets surface in MonoGame

texts:
I have a 3D planet and I would like to place models on the planet and have them start with a base rotation relative to the planet surface at their location. So a model at the north pole will have zero rotation, and one at the south pole will be upside down etc.

I have some code that kind of works but not very well so i guess that there are errors with the math. I'm trying to calculate the Pitch based on the angle between the location and Y axis, and the Roll based on the angle between the location and X axis.

Can some one please help get the rotation calculation working?

public Matrix CalculateBaseRotation(Vector3 vLocation)
{
   // Calculate Up Direction (Assumes planet position is Vector.Zero)
   Vector3 WorldUp = Vector3.Normalize(vLocation);

   // Compute Dot Products relative to Y and X axis
   float Dot_A = Vector3.Dot(Vector3.UnitY, WorldUp);
   float Dot_B = Vector3.Dot(Vector3.UnitX, WorldUp);

   // Calculate Angles From Dot Products
   float Angle_A = (float)Math.Acos(Dot_A);
   float Angle_B = (float)Math.Asin(Dot_B);

   // When Z is negative, invert Angle A to prevent curve following S pattern
   // This seems hackish, there must be a more mathematically elegant solution
   if (WorldUp.Z < 0)
       Angle_A = MathHelper.TwoPi - Angle_A;

   // Invert Arc Of AngleB
   if (WorldUp.Y > 0)
       Angle_B = MathHelper.TwoPi - Angle_B; // Keeps curve to planet surface
   else
       Angle_B = Angle_B + MathHelper.Pi; // Prevent flipping upside down in southern hemisphere

   // Clamp Angles
   Angle_A = MathHelper.WrapAngle(Angle_A); // PITCH
   Angle_B = MathHelper.WrapAngle(Angle_B); // ROLL

   // Create Base Rotation Matrix
   // AngleA Should Be Second, AngleB Should Be Third
   return Matrix.CreateFromYawPitchRoll(0, Angle_A, Angle_B);
}


texts:
Imagine the blue part of this picture is streets and navmesh.
the red object is a car with navmeshAgent.
the green circles are the colliders set as triggered and they are the destination of the car.
when the game starts the car will choose one of them and go to that , after reach that it will choose another one randomly so it means the car will go through all of this forever.
now the problem is sometimes when car reach's one them and choose another since it will choose the closer path to next destination sometimes it will have to turn back which its not realistic and doesn't make sense.

as you can see in this example when reach that point since the middle one is closer from where the car is triggered it will turn back and the red arrow is wrong path ,  instead it should go through the green arrow and that's the correct path.
how can i do something to not to turn back instead find another way?


texts: What's the difference between Camera::getPosition() and Camera::getPositionForViewUpdate()?

texts:
In Ogre3d, what's the difference between methods  Camera::getPosition() and Camera::getPositionForViewUpdate(), official documentation doesn't says much:

/** Get the derived position of this frustum. */
const Vector3& getPositionForViewUpdate(void) const;

/** Retrieves the camera's position.*/
const Vector3& getPosition(void) const;

Thanks!


texts: How a "Collision System" should be implemented?

texts:
My game is written using a entity system approach using Artemis Framework. Right know my collision detection is called from the Movement System but i'm wondering if it's a proper way to do collision detection using such an approach.

Right know i'm thinking of a new system dedicated to collision detection that would proceed all the solid entities to check if they are in collision with another one.

I'm wondering if it's a correct way to handle collision detection with an entity system approach? Also, how should i implement this collision system?

I though of an IntervalEntitySystem that would check every 200ms (this value is chosen regarding the Artemis documentation) if some entities are colliding.

protected void processEntities(ImmutableBag<Entity> ib) {
    for (int i = 0; i < ib.size(); i++) {
        Entity e = ib.get(i);
        //check of collision with other entities here
     }
}


texts: Are virtual calls worth it for game entity management?

texts:
I have seen a lot of game programming tutorials doing this:

//our base class
class entity
{
   /*virtual methods and data common to all entities
   and a 4 Byte virtual pointer*/
};

//Some other class inheriting those calls and data
class Player : public entity
{
   //extra methods and calls specific to class a 4 Byte virtual pointer
};

and thousands of Gameobject classes doing the same thing. What it does that it allows us to make a list of all objects and update and render (and some other things) it in a single loop.

But I have problems with this approach when I want to do something with a single object. suppose we have a list of all entities...

list<entities*> entities = {
new Player0(its properties),
new Enemy0(its properties),
new Player1(its properties),
new Stone0(its properties),
.... and so on
};

and now I want to stop updating Player1 for some reason. Now Either I can assign an ID to each object so that I can use "if" condition to stop updating it or I can have a reference to that object before pushing it to the list which is messy because I cannot have refrences to all of objects. Also lets consider that 4 byte additional size for those objects because of virtual calls.

An Alternative can be to have only references to objects...but again its thousands of objects we are talking about here so It will be hard to manage.

How to handle this problem?


texts: Fast method of detecting whether point is inside mesh

texts:
I'm trying to construct a 3d object from a large number of particles. I think this is called BVH (Bounding volume hierarchy). I figured the best way is to draw the particles inside the mesh, then let them drop down. Repeat as often as produces suitable results.

For this, I need to check for each point whether they lie inside the 3d model. I might be using something in the order of 1 million particles, so the point-in-mesh code needs to be fast. I have some clues about creating a 2d stencil projection first, and checking against that. But I'm not really sure what's the smart way to go about this.


texts:
I'm doing line-triangle intersection. I have found the intersection point (vector) on the plane. All I need to do now is work out whether the point is inside the triangle it collided with (not the plane the tri is on)

The line is represented by two 3D vectors, the triangle 3 points and the collision point another vector. If it's any help, I've been reading through this article. I've actually managed to do most of it. I'm just stuck on the last bit which is working out whether the point is inside the triangle.

I've read stuff about summing the angles of 3 internal triangles, but that's extraordinarily slow - can someone help me out?

Thanks,

James


texts: How to know if two surface are in the same direction?

texts:
In my code I creat a Mesh that are composed by multiple tile. those tile can have edge that are shared, and I need to know if the normal of the tile that have shared edge have the same direction, because I calculat the normal of the edge to smooth the light. before I used the Vector.Dot() , but I've sometimes two tile that have a curve that make impossible to use this function as you can see in the 4th image.
and the only information that i have in the calcul is the 2 normal of the tile.
 img 1 : diferent direction
 img 2 : diferent direction
 img 3: same  direction
 img 4: same  direction
 img 5: same  direction


texts: How to prevent audio files and particle system from playing automatically when loading the game?

texts:
I am using Unity. I have attached an audio-file (via Audio Source) to an empty object. I will play the game this plays automatically. The same is happens with the particle system.
I would like to know how to prevent this from occurring.
Thanks in advance.


texts: Where can I find free motion capture footage?

texts: Are there any repositories of free motion capture footage? Or maybe just libraries of animations.


texts: Why is unity's RaycastHit2D contact point is slightly off

texts:
This is a small test I made, basically I have a simple BoxCollider2D that has the top surface aligned with the x axis. It's just a 1x1 cube placed at (0, -0.5). Now when I cast a ray down from position (0, 1) I would expect the resulting RaycastHit2D's contact point to be (0, 0) however when I log the contact point, it shows it is slightly over the actual surface at (0, -2.384186E-07).

So the question is, why does this happen? Also, can it be fixed somehow (like tweaking settings or something)?


texts: Game Mechanics Suitable for a Game about Issues of Immigrations

texts:
So, I'm working on a video game design concept, dealing with the problems of an immigrant family and how they will try to blend in the society. The universe is a fictional universe.

I was wondering what game systems/mechanics/genres are suitable for such a concept? How can I use the mechanics in a sense that will be coherent with the narrative that I'm trying to tell?


texts:
In the game Viva Pinata, cute virtual animals have color changing paper cut like furs.

It didn't seem like using shell rendering because there are LOTS of animals in a scene and shell rendering each every one of them to render these furs sounded like a daunting process for a game.

I tried to build 3d model with each triangle but that didn't seem like right solution either.

I am out of my tricks in my pocket.


texts:
I'm using Godot and I want to set an outline on the tile which is currently being hovered over, but I'm not sure whether to do it as a seperate tilemap which is hidden until it is hovered over or just display a highlighted tile sprite when the tile is hovered.

This is an example of how I sorta want it.

Any advice?


texts: Assigning a colour to imorted obj. files that are being used as default material

texts:
I am having a problem with assigning a colour to the different meshes that I have on one object.
The technique that I have used is the first approach on this site.
Is it possible to export a simulation (animation) from Blender to Unity?

So what I would like to do is the following.
I have about 107 meshes that are different frames from my shape key animation of my blender model.  What I would like to have is that the first mesh will be bright green and up to the  40th mesh the colour turns to be white /greyish...

the best would be if I could assign every mesh by hand a colour, however they are all default materials. And if I assign the object a colour, the whole "animation" is going to be in that colour


texts: Is a dynamic enviroment map using pincushion curvilinear perspective projection possible?

texts:
I'm wondering if it is possible to generate a dynamic spherical environment map using a single frame render using a pincushion curvilinear perspective projection matrix (phew, that's a mouthful)?

I've been researching this for a few days now and the closest thing I can find is a curvilinear perspective but it isn't a commonly used projection matrix so there isn't any help I was easily able to find and I still don't know if it supports a full circle FOV.

Why?

The standard perspective matrix but it begins to look very strange and distorted above 180 degrees vertical FOV and completely fails to render when approaching 360 degrees. So instead most games render the scene six times using 90 degree FOV facing the faces of a cube.

Rendering the scene 6 times seems like a waste if it might be possible to simply imagine a camera that has a 360 degree view across both axis and then render that to a spherical environment map.


texts: Reading from a staging 2D texture array in DirectX10

texts:
I have a DX10 program, where I create an array of 3 16x16 textures, then map, read, and unmap each subresource in turn. I use a single mip level, set resource usage to staging and CPU access to read. Now, here is the problem:

Subresource 0 contains 1024 bytes, pitch 64, as expected.
Subresource 1 contains 512 bytes, pitch 64.
Subresource 2 contains 256 bytes, pitch 64.

I expect all three to be the same size. Debugging output is enabled, but not reporting any warnings or errors. Am I missing something, or might this be some sort of driver issue?

Here is the code. The language is Nemerle, but C# and C++ would look almost the same. I have looked through the generated code, and am fairly confident the problem is not language-related.

def cpuTexture = Texture2D
    ( device
    , Texture2DDescription() <-
    {
        Width     = 16;
        Height    = 16;
        MipLevels = 1;
        ArraySize = 3;
        Format    = Format.R32_Float;
        Usage     = ResourceUsage.Staging;
        CpuAccessFlags    = CpuAccessFlags.Read;
        SampleDescription = SampleDescription(count = 1, quality = 0);
    }
    );
foreach (subresource in [0 .. 2])
{
    def data = cpuTexture.Map(subresource, MapMode.Read, MapFlags.None);
    Console.WriteLine($"subresource $subresource");
    Console.WriteLine($"length = $(data.Data.Length)");
    Console.WriteLine($"pitch  = $(data.Pitch)");
    cpuTexture.Unmap(subresource);
}


texts: How can I move an object around the screen in cocos2d?

texts:
I am trying to move the object around the screen using cocos2d. I have this code:

-(void) move
{
  CGFloat upperLimit = mWinSize.height - (mGunda.contentSize.height / 2.0);
  CGFloat upperLimit1 = mWinSize.height;
  CGFloat lowerLimit = (mGunda.contentSize.height / 2.0);
  CGFloat RightLimit = mWinSize.width - (mGunda.contentSize.width/2.0);
  CGFloat Right = (mGunda.contentSize.width/2.0);

  if(mImageGoingUpward ) {
    mGunda.position = ccp( mGunda.position.x, mGunda.position.y + 5);

    if(mGunda.position.y >= upperLimit) {
      mImageGoingUpward = NO;
      mHori = NO;
    }
  } else {
    mGunda.position = ccp( mGunda.position.x, mGunda.position.y - 5);
    if(mGunda.position.y <= lowerLimit) {
      mGunda.position = ccp(mGunda.position.x +5, lowerLimit);
    }

    if(mGunda.position.x >= RightLimit) {
      mGunda.position = ccp(mGunda.position.x, mGunda.position.y+10);
      mHori = YES;
    }

    if(mHori) {
      if(mGunda.position.y >= upperLimit) {
        mGunda.position = ccp(mGunda.position.x - 5,mGunda.position.y);
      }
    }
  }
}

It is supposed to move the object around the screen. The code mostly works, but it doesn't move the object from the top-right of the screen to the left of the screen.


texts: Picking 3D object with Mouse when using Camera Zooming in XNA 4.0

texts:
I've tried to figure out how to do picking with the mouse, and things work great when zoomed in all the way with the camera (Third Person Camera). And it works perfectly when using First Person Camera.

However, when using Third Person camera, if I zoom out the camera view, the picking stops working, it gives me incorrect locations and I start picking on a limited set of items in the center of the screen.

It's like I have to figure out how to scale the picking based on the zoom that I'm performing. Here's my code for picking right now. The point is to have the "targetPoint" be the position you are picking in the world coordinates:

if (_gameManager.Camera is FirstPersonCamera)
{
    // Get the building location from the look vector of the camera
    targetPoint = _player.Position + (_player.LookVector * x);
}
else if (_gameManager.Camera is ThirdPersonCamera)
{
    // Get the building location based on the mouse cursor
    Vector3 nearsource = new Vector3((float)_player.PreviousMouseState.X, (float)_player.PreviousMouseState.Y, 0f);
    Vector3 farsource = new Vector3((float)_player.PreviousMouseState.X, (float)_player.PreviousMouseState.Y, 1.0f);

    Vector3 nearPoint = _gameManager.GraphicsDevice.Viewport.Unproject(nearsource, _gameManager.Camera.Projection, _gameManager.Camera.View, Matrix.Identity);
    Vector3 farPoint = _gameManager.GraphicsDevice.Viewport.Unproject(farsource, _gameManager.Camera.Projection, _gameManager.Camera.View, Matrix.Identity);

    Vector3 direction = farPoint - nearPoint;
    direction.Normalize();

    targetPoint = _player.Position + (direction * x);
}

The x I'm adding is because I'm searching a set of targetPoints for a matching 'block' in the game world. That part is of no consequence I believe. The rest is for picking a targetPoint that will match a tile in the terrain made up of square blocks.

When I'm zooming in and out, the camera View is recalculated this way:

Matrix rotationMatrix = Matrix.CreateRotationX(UpDownRotation) * Matrix.CreateRotationY(LeftRightRotation);

// Create a vector pointing the direction the camera is facing.
Vector3 transformedReference =
            Vector3.Transform(new Vector3(0, _zoomFactor, _zoomFactor), rotationMatrix);

// Calculate the position the camera is looking from.
_positionVector = transformedReference + _avatarPosition;

// Set up the view matrix and projection matrix.
View = Matrix.CreateLookAt(_positionVector, _avatarPosition, Vector3.Up);

If anyone could help me out, I'm a bit stuck with this one, I've tried a few things and only made things worse. I have yet to find out why none of the picking examples I've found in XNA creators forums or any of the ones found here mention anything about the camera zoom level compared to the game objects that are being picked.


texts: Can one build a game based on something that already exists and make money off of it?

texts:
Possible Duplicate:
  Is it legally possible to make a clone of the game?

I was planning on producing a game but then I had to stall. I have an idea to make a game, but its very similar to a game already out there. If I made my own graphics, audio and use my own code, would I be allowed to sell it?


texts: Should I (and how to) avoid using global classes

texts:
I have been having fun learning java for years, did a little bit of OOP tutorials and this is the first time I attempt to make a real project. The project is very similar to some top down view tabletop management game with very little graphics. Oddly every thousand line of code I hit my head on a wall and wonder if I need to restructure everything. For example I restructured once to try and adopt some concept of MVC, which I had no knowledge of when I started. I am glad I did.

The wall now : I started reading how we should use global and singleton sparingly when I suddenly could not save my game since I had created a new instance that had static fields (using GSON to save my Game object).

My project structure

App : gameloop, has Engine class, calls Engine.updateUI() and engine.updateGame()
Engine is the main controller that has access to all other controllers, creates the game object and updateUI() and updateGame() methods
Game : contains every object that represent the state of the game so that I can save and load it
MyData class is a global class that just loads a bunch of text files and provides data for the game but does not need to be saved

So lately I created a class called Finances that had static fields such as cash, waterBill, electricityBill... I can only ever need one instance of Finances in my game so I thought it would be neat to be able to do something like Finances.addCash() or if Fiances.getCash() == enough doSomething from anywhere in my code, from any controller, to enable and disable buttons for example.

I have another similar class called Updater that has static booleans as flags to schedule an update on certain part of the UI instead of having every UI elements update and query the model 60 fps.

Some solutions

Add some code to save and load the values of those static fields;
change the fields to non-static and give Game another parameter called finances that will only be created once.

I was going with the second approach for a while but I realized I was just passing Engine engine everywhere to have access to everything like engine.getGame().getFinances().getWaterBill().pay()

I feel like this is just like a global variable but more complicated. Here I am not hoping to code the best code with the best structure and all best practices. I am just looking to improve and learn in a fun way. Most articles I found just end "anyway if you end up with needing many singletons or globals your code probably smells". That did not help me find a solution.


texts: I am creating a Tetris clone on Khanacademy, will I get into trouble?

texts: For those don't know, Khanacademy is an education site that also has lessons on simple computer programming and allows you to publish your own games that are made on the website.


texts: How can I calculate respective 2D world/mouse position through different resolutions?

texts:
I have been at this game of trial-and-error for days now. I cannot find a consistent method to calculate the respective mouse position in my game world after the calculations are done to stretch the game's render view to the current resolution. I've seen other, similar questions and answers on this site, but after looking at them long and hard, I can't translate the answers to my project.

I'm using XNA. First, I render everything to a RenderTarget2D at a resolution of 800x600. Then I render said RenderTarget to the screen by calculating it's size and location through a method that returns a Rectangle:

public Rectangle CalculateRenderTargetPosition()
    {
        Rectangle rec;
        Single preferredAspect = Globals.RenderSize.Width / (Single)Globals.RenderSize.Height;
        Single outputAspect = Globals.WindowSize.Width / (Single)Globals.WindowSize.Height;
        if (outputAspect <= preferredAspect)
        {
            // output is taller than it is wider, bars on top/bottom
            Int32 presentHeight = (Int32)((Globals.WindowSize.Width / preferredAspect) + 0.5f);
            Int32 barHeight = (Globals.WindowSize.Height - presentHeight) / 2;
            rec = new Rectangle(0, barHeight, Globals.WindowSize.Width, presentHeight);
        }
        else
        {
            // output is wider than it is tall, bars left/right
            Int32 presentWidth = (Int32)((Globals.WindowSize.Height * preferredAspect) + 0.5f);
            Int32 barWidth = (Globals.WindowSize.Width - presentWidth) / 2;
            rec = new Rectangle(barWidth, 0, presentWidth, Globals.WindowSize.Height);
        }
        return rec;
    }

The Camera's position is rendered during rendering to the RenderTarget2D through a Matrix in the SpriteBatch.Draw method, so there's nothing weird going on there. The Camera itself works fine at any resolution.

After days of guesswork, this is the closest method I've got:

Rectangle r = Globals.Draw.CalculateRenderTargetPosition();
MouseState ms = Mouse.GetState();

Single aspect = Globals.WindowSize.Width / (Single)Globals.WindowSize.Height;
Single pmx = (ms.X - r.X);
Single pmy = (ms.Y - r.Y);
Single mx = (pmx == 0 ? pmx : pmx / aspect);
Single my = (pmy == 0 ? pmy : pmy / aspect);
Vector2 pos = Vector2.Transform(new Vector2(mx, my),
    Matrix.Invert(Globals.Camera.GetViewMatrix()));
Globals.RelativeMousePosition = new Vector2(pos.X, pos.Y);

Even if this is almost close enough, it's still off. I don't know if there's some magical Matrix method I don't know about or if I just suck at math.


texts:
I have been following a tutorial about setting up vulcan on macOS and have been having trouble. I think it might have something with the versions. I am using 1.1.101.0 and the tutorial uses 1.1.73.0

here is my /.bash_profile


texts:
I want to make a parallax effect in Unity 3D with gyroscope like the one on this site:
http://matthew.wagerfield.com/parallax/

I found an asset, but it is too expensive.

So I need a script which I can set to the GameObject, so it would move depending phone's gyroscope.


texts:
I am currently programming my first game in Java and I'm having trouble structuring it.
My biggest concern is regarding the game loop.
Currently I have implemented a class with only a main function which first initializes all of the variables and then goes into a game loop. Here is the structure of the code:
public static void main(String args[])

//Initializing all the variables

//Main game loop

while(true)
{
  if (mouse is pressed)
  {
    do something
  }

  if (mouse is released)
  {
    do something
  }
  ......
}

The problem is that the "do something" parts are quite lengthy and my code looks quite messy. I would like to turn them into methods, however I am not really sure how to do it.


texts: Move a point to another, along an elipse

texts:
according to this picture, I want to move my yellow object, smoothly to the red one. And I want to have an eliptic trajectory in relation to my center point.

So for now I'm having this code:

yellowPoint.position = Vector3.SmoothDamp(yellowPoint.position, redPoint.position, ref currentVelocity, dampingMove);

How can I change it to add the elipse, depending on a third center point ?
the itinial code can change of course.

Thanks you !


texts: Bones Animation - Matrices and calculations

texts:
We are 'on final' when it comes to finishing the project, but just before implementing the animation system.

Our Client decided to choose "Bones Animation" - which is that I should export each  Transformation Matrix ( matrix4x4 rotation+translation ) for every frame and for every bone that this animated object has.

Objects in our game are animated with 3DS Max Physique Modifier, so we will have bones / weighting data per vertex. But I will simplify things here just to get a bit of light on this subject.

I would like to split this post into 2 points, where :

Exporting bones matrices for every frame

treats about the correct method of exporting the bones positions for later animation purposes, where i have to 'move' and 'rotate' every vertex influenced by this bone to bone position at frame X.

Calculating final vertex position

treats about proper matrices operations to calculate new vertex position according to bone transformation in frame X.

1. EXPORTING BONES MATRICES FOR EVERY FRAME

Do I understand correctly that while exporting the animated object I should:

  Grab BONE transformation matrix at frame 0 and Invert this matrix
  Grab BONE transformation matrix at FRAMEx
  Multiply 1 * 2 to get the transformation offset of the BONE at FRAMEx

[pseudocode]
// Animation export

// For each frame, export bone transformation offset
for(int iFrame = 0; iFrame < vFrames.size(); iFrame++)
{
    // For every bone in the object
    for(int iBone = 0; iBone < vBones.size(); iBone++)
    {
        // Grab transformation matrix for this bone at frame 0 and inverse it
        Matrix3 matBoneMatrixAtStart = pNode->GetObjectTMAfterWSM( 0 );
        matBoneMatrixAtStart.Inverse();

        // Grab transformation matrix for this bone at frame iFrame
        Matrix3 matBoneMatrixAtCurrentFrame = pNode->GetObjectTMAfterWSM( iFrame );

        // Multiply Inversed Transformation Matrix of this bone at frame 0 - with
        //  current frame transformation matrix
        Matrix3 matBoneTransformationOffset = matBoneMatrixAtStart
                                              * matBoneMatrixAtCurrentFrame ;

        // Save matBoneTransformationOffset - vertex will be multiplied by this
        //  matrix for animation purposes
        fwrite(.....)
    }

}
[/pseudocode]

Will that be enough ? Or there is something I am missing here?

2. CALCULATING NEW VERTICES POSITIONS ( FINAL VERTEX POSITION AT FRAME X)

Later on, when rendering, object vertices are going to be multiplied by exported bone transformation matrix for actual animation frame, and then multiplied by
 this whole model transformation matrix to place the object in correct position inside the level :

[pseudocode]

Update()
{
    // The model transformation matrix describing the position of
    //  the model in the level
    matModelTransformationMatrix

    // Calculate new vertex position according to it's bone transformation offset
    NewVertexPosition = (OriginalVertexPosition * matBoneTransformationOffset[iFrame])
                           * matModelTransformationMatrix;

    // Increment the frame for testing purposes
    iFrame++;
}

[/pseudocode]

Am I thinking correct here? So, Having bone transformation offset for frame X, multiplying every vertex affected by this bone by this offset should result in a vertex transformed exactly as this bone right?


texts: Creating a black light (ultraviolet) shader?

texts:
I am interested in the algorithm for color picking that would ideally allow to choose what color range will be highlighted and what color range will be faded.

I can sort-of understand how to make it look like black light effect, but I wonder if there is actual research out there on how to make it properly. What is the technique for rendering a black light effect?

Another question is highlights: How do you handle highlights? Do you ignore them completely or link their power to the luminess color of the surface?


texts: Question about mipmaps + anisotropic filtering

texts:
I'm a bit confused here and maybe someone can explain this to me. I created a simple test texture for my terrain which is nothing more than a solid green color with a black grid overlayed on top of it. If I look at the terrain in the distance with mipmapping on and linear filtering, the grid lines become blurry fairly quickly and further back the grid is pretty much invisible. With these settings, I don't get any moire patterns at all. If I turn on anisotropic filtering, however, the higher the anisotropic level, the more the terrain looks like it did with without mipmapping. The lines are much crisper nearby but in the distance I start to see terrible moire patterns.

My understanding was that mipmapping is supposed to get rid of moire patterns. I've always had anisotropic filtering on in every game I play and I've never noticed any moire patterns as a result, so I don't understand why it's happening in my game.  I am using logarithmic depth however, could that be causing any problems?  And if it is, how do I resolve it?

I've created my sampler state like so (I'm using slimdx):

ssa = SamplerState.FromDescription(Engine.Device, new SamplerDescription
{
       AddressU = TextureAddressMode.Clamp,
       AddressV = TextureAddressMode.Clamp,
       AddressW = TextureAddressMode.Clamp,
       Filter = Filter.Anisotropic,
       MaximumAnisotropy = anisotropicLevel,
       MinimumLod = 0,
       MaximumLod = float.MaxValue
});

Point Filtering

Anisotropic 1

Anisotropic 8

Anisotropic 16

Anisotropic 16 at an angle


texts: Stop character from moving after reach his destination?

texts:
my script is for character moving to the certain point on the terrain. To get this point I have to use mouse. When I click on the terrain, my character goes there. Now, If he reach his point and something like enemy come to push him, he moves away from his point !!? What I want is to make him stop there and no power in the world could move him.

private NavMeshAgent mAgent;
public Vector3 point_;
public float mark;
public bool actives;

void Start()    {
    mAgent = GetComponent<NavMeshAgent>();

}

// Update is called once per frame
void Update()    {
    Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit mousePoint;
    if (Input.GetMouseButtonDown(0))
    {
        if (Physics.Raycast(mouseRay, out mousePoint, 100))
        {
            point_ = mousePoint.point;
            mAgent.SetDestination(mousePoint.point);
            mark = Vector3.Distance(point_, gameObject.transform.position);
        }

    }

}


texts: How do I determine which voxels to test for collision against the player?

texts:
I've implemented Minkowski subtraction to test whether (and where) two AABBs collide, independent of framerate/time-step, in my Minecraft-like game.

But since there may be tens of thousands of voxels, I'm realizing I can't just test everyone of them. Is there an alternative to just scanning for nearby voxels? I worry that if I just do collision for voxels within a fixed range, then I've undone the framerate independence that I had sought.


texts: Managing game progress - states, stages, or flags

texts:
I am creating an rpg. So far I've used a global game stage as well as individual npc stages (increased when completing a quest for example) to control the "stage" the game is in. I.e if I have a log blocking a road, If game stage is > 10 then the log should not be there anymore.

This worked fine for basics but I want more control. And was considering a system with flags. For example a static class with booleans like "isLogRemoved", that I can use on top of stages to get more control. Plus it would be easy to save/load.

Before I make my own system along these lines I wanted to ask you more experienced people if there is a "proper" approach to this problem. Take a game like Zelda for example, where there are so many things that act differently depending on the stage (or state) of other objects in the world. Does anyone have a clue what a system like that looks like or how it works?

Hope I'm making sense. Having a hard time formulating this one.


texts: I just filled submission form for google play protect for my new-developed game. the problem is with URL download link. I used file.io to generate a direct download link. it worked fine for the first time but now error 404 for "not found" is shown. I re-submit a new form with same information but different URL to download my APK (I used DropBox to generate direct link and bit.ly for shortening the link) but google told me via email that it doesn't need to re-submit. I know that the the process for accepting my game could last for 7-10 days. what do you suggest?


texts:
I have a question about game world rendering. What is the best way to render background graphics such as grass and trees in 2D for your game?
Normally I would use array of tiles where every grass tile and tree are but I have big game world and for that this seems like too memory hungry solution
So what I need is nearly infinite game world rendering. the game I'm making is completely tileless and the game objects move using vectors
Also I need to render rivers
Some example pictures of what kind of game world I mean: maps


texts: Assign type to an entity in Entity-Component System (super entity - syntactic sugar)

texts:
I have created ECS framework from scratch using C++.

Everything works fine, but I think my code is not so cute (at #1):-

class RocketComponent{
    Entity mainBodyGraphic;
    Entity topGraphic ;
};
//inside some system (script-like)
void createRocket(){
    Entity mainBodyGraphic = graphicFactory->createCylinder();
    Entity topGraphic = graphicFactory->createCone();
    //^ internally create entity (with graphic component and others),
    //         then attach together
    Pointer<RocketComponent> rocket  = create<RocketComponent>();
    rocket->mainBodyGraphic = mainBodyGraphic;
    rocket->topGraphic = topGraphic;
    //.... other logics ....
}

void showDamage(Entity rocket){
     Pointer<RocketComponent> rocket  = rocket->get<RocketComponent>();
     systemGraphic->setColor(rocket->mainBodyGraphic,RED);   //#1
}

#1 is ugly.
In my dream (Object-oriented style), #1 could be :-

rocket->mainBodyGraphic->setColor(RED);                      //#1

The above line is far easier to read and code.     It is also less error-prone.

The Change (super entity)

I plan to change my code to support it, but I don't want to lose any disadvantage of ECS.
Therefore, I will create super entity.

For example:-

I create a new super Entity class named GEntity (graphic entity).
I provide a converter (operator=()) between Entity and GEntity.
Whenever a function just want Entity, I can pass GEntity instead, and vice versa!
graphicFactory->createCone() and similar functions will return  GEntity instead of Entity.
The field in RocketComponent will be GEntity mainBodyGraphic;.
Entity has no access to game logic like before, but GEntity can access all game logic/system.

Here is my adoption (future plan / promise to myself):-

In GEntity, I can add all syntactic sugar functions e.g. setColor() as much as I want.
I will use GEntity only when logical type of entity is very obvious.
I will also create PEntity = Physic body, because its type is also obvious.
I may also create other types of super entity if its type is very obvious && I want the syntactic-sugar.

Here is the result (change marked with $):-

class RocketComponent{
    GEntity mainBodyGraphic;      //$
    GEntity topGraphic ;          //$
};
void createRocket(){
    GEntity mainBodyGraphic = graphicFactory->createCylinder(); //$
    GEntity topGraphic = graphicFactory->createCone();          //$
    Pointer<RocketComponent> rocket  = create<RocketComponent>();
    rocket->mainBodyGraphic = mainBodyGraphic;
    rocket->topGraphic = topGraphic;
    //.... other logics ....
}
void showDamage(Entity rocket){
     Pointer<RocketComponent> rocket  = rocket->get<RocketComponent>();
     rocket->mainBodyGraphic->setColor(RED);                    //$
}

Concern (my fear)

I feel that I am violating some ECS rules.
I am probably destroying good ECS abstraction and design pattern in favor of my indolence.

I have already refactored some of my code to the new way.
It looks nice and neat.   I think I am biased.

Question

What are disadvantage of this approach?
What are things (potential issue) that I should concern and prevent?
What is the name of this technique/design-pattern (if any)?


texts: In Unity3D, how do I create an efficient scratch card effect?

texts:
I want to create a scratch-card-like effect in new Unity UI's new Image tag.  I know it's possible with setPixels, but that's prohibitively expensive on mobile devices.

Something like this:

I'd like the user to be able to drag on any part of the image to "scratch off" the top layer and reveal the content underneath it.

How can I do this?


texts:
public void OnGamePause()
{
    Debug.Log("OnGamePause in PauseController");

    if (rb != null)
    {
        velocity = rb.velocity;
        angularVelocity = rb.angularVelocity;
        Debug.Log("Pause vel. = " + velocity + "Avel. = " + angularVelocity);
        rb.Sleep();
        Paused = true;
    }
}

public void OnGameResume()
{
    Debug.Log("OnGameResume in PauseController");

    if (rb != null)
    {
        Debug.Log("Resume vel. = " + velocity + "Avel. = " + angularVelocity);
        rb.velocity = velocity;
        rb.angularVelocity = angularVelocity;

        rb.WakeUp();
        Paused = false;
    }
}

Can anyone give me any idea what might be changing velocity?


texts: Unity crash upon opening a specific scene

texts:
I have this one specific scene that I spent over 20 hours building. But as of today when I attempt to open it unity crashes. I have opened the error log and it states:

Unity.exe caused an Access Violation (0xc0000005)
  in module Unity.exe at 0033:4150123b.

Error occurred at 2017-09-22_200636.
C:\Program Files\Unity\Editor\Unity.exe, run by MarcR.
62% memory in use.
16257 MB physical memory [6165 MB free].
32641 MB paging file [18590 MB free].
134217728 MB user address space [134213224 MB free].
Read from location 00000098 caused an access violation.

I have tried running the program as administrator, updating the unity editor and cleaning the cache.

The funny thing is that I am actually able to open the scene additive to my current scene.

Can anyone tell me whats going on?

(On an end note I did not want to post ALL of the error log if you need to see please comment and I will, of course, link it)


texts: GLSL/SFML - Only make portion of texture alpha

texts:
I'm trying to take a portion of the current texture and turn it to 50% transparent. I send in four values, signifying the rectangle I want to make transparent. It seems every time, however, that coord.x/coord.y are set to (0, 0), resulting in the entire image being transparent when I send in any rectangle that starts at (0, 0).

I'm still new to GLSL and and probably approaching this wrong. Any pointers on the correct approach would be greatly appreciated!

Values being sent in

sprite.Shader.SetParameter("texture", sprite.Texture);
sprite.Shader.SetParameter("x1", 0);
sprite.Shader.SetParameter("x2", 5);
sprite.Shader.SetParameter("y1", 0);
sprite.Shader.SetParameter("y2", sprite.Height - 1); // sprite.Height = 32

transparency.frag

uniform sampler2D texture;

uniform float x1;
uniform float x2;
uniform float y1;
uniform float y2;

void main() {
    vec2 coord = gl_TexCoord[0].xy;

    vec4 pixel_color = texture2D(texture, coord);

    if ((coord.x > x1) && (coord.x < x2) && (coord.y > y1) && (coord.y < y2))
    {
        pixel_color.a -= 0.5;
    }

    gl_FragColor = pixel_color;
}


texts: Is 3d game development advantageous/possible in SDL2?

texts:
I think this is not appropriate, but as the given video in the link, the youtuber name Bisqwit creates his own 3d engine from scratch in C and SDL2. How much is this advantageous is real 3d game development and following his idea can a first practice project? (rather than just starting with OpenGL)?

https://www.youtube.com/watch?v=HQYsFshbkYw


texts:
How would it be possible to test for the presence of the ODK at run time?
Currently I took this approach:

private activityDelegate delegate;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Need to test for the presence of the ouya ODK here
    {
        delegate = new OuyaDelegate(savedInstanceState);
    }
}

But maybe there is a better way of doing this than in the main activity?


texts:
I'm writing a 2D game with an internal 3D space. The view is 3/4 view. I've run into trouble with the render order of entites.
Context: The world uses a tile system, like a 3 dimensional lattice, each tile is a 1x1x1 space. Entities have a 3D coordinate position and do not snap to tiles(may straddle two tiles). Entities have their own width, height, and depth, all entities are strictly oblongs and do not rotate(only exist in right angles). Since the view angle is fixed and there is no perspective, the graphical representation of the tiles and entities are all 2D images(they are all sprites)
Question: How do I code for render orders in a 3/4 view?
So far, I've defined the render order using the y and z coordinate of the entity(I believe x coordinate is irrelevant in 3/4 view). However, it quickly dawned how using a single point to define the layer of an entity with a height and depth was bound to have issues. This is illustrated in the following image:

The horizontal axis is y, while the vertical axis is z. The dashed line represents the view angle.
The blue box and green box should be rendered above the red box. However, when the render order is determined by either the y or the z coordinate of the entity's origin point(highlighted), it is impossible for the system to be consistant.
For instance, if the renderer renders from lowest to highest(layer based on z coordinate), the red box would cover the green box, which is incorrect. If the render renders from back to front(layer based on y coordinate), the red box would appear on top of the blue box, which is incorrect. A mixture of y and z coordinate(e.g. y + z = layer) would be inconsistant also, though it does agree with the example shown.
Without assumptions about the features of the game I am creating, is there a way to have a system that can consistantly order render layers correctly, given information of 3D coordinate position and dimensions of all entities? Also given that each entity is represented as a flat, 2D sprite?
I have encountered numerous sites warning people away from 3D, since it is "orders of magnitude" harder than 2D. Could I walk the tightrope and introduce some 3D elements to solve this issue, while keeping the game 2D and in 3/4 view angle? Thanks in advance.


texts: Dynamic Events in an Entity Component System

texts:
My game makes extensive use of libGDX's Entity Component System Ashley, and my game world (including all levels and areas) is created with Tiled.

In Tiled, I have an object layer where all of my entities are added (as rectangles, although the shape does not matter). Each object properties links to a YAML file containing serialized components which are deserialized when the Entity is added. This system works well, and I want to use a similar method for handling all types of map events, although I don't know of a way to do this.

I want to create dynamic events that:

Have one or more causes
Have one or more effects for each cause

Where a cause is something such as a player interacting with a switch, and an effect is a door opening. One or more cause could be, for example, that the player must have a specific item and interact with a switch.


texts: Unity 2D - Problem with player running ON wall instead of falling

texts:
I´m having a problem with my game (yes, I'm new with Unity).
I'm trying to make a simple 2d platformer and I ran into this situation:

Youtube Link

As you can see, when the player hits the BoxCollider from the side, it tries to get a hold of it instead of just keep going down...

These are the properties of my player:

And the block only has the default box collider.

Any ideas?
Thanks!


texts: How to print Depth to a Texture2D and then read it in the next pass on a shader in DirectX11

texts:
I'm programming a two-pass effect in DirectX 11 (SharpDX). It's supposed to write the depth to a texture in the first pass and then use that texture to extract data on the second one in the pixel shader.

What I get is a white screen, with nothing but the interface and I don't know why nothing is being printed. What could be the problem? I would say I should get at least something from the Depth Texture.

This is how I'm setting the depth texture values:

this.depthBuffer = new Texture2D(device, new Texture2DDescription()
        {
            Format = Format.R32_Typeless,
            ArraySize = 1,
            MipLevels = 1,
            Width = (int)host.ActualWidth,
            Height = (int)host.ActualHeight,
            SampleDescription = new SampleDescription(1, 0),
            Usage = ResourceUsage.Default,
            BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
            CpuAccessFlags = CpuAccessFlags.None,
            OptionFlags = ResourceOptionFlags.None,
        });

this.depthBufferShaderResourceView = new ShaderResourceView(this.device, this.depthBuffer, new ShaderResourceViewDescription()
        {
            Format = Format.R32_Float,
            Dimension = ShaderResourceViewDimension.Texture2D,
            Texture2D = new ShaderResourceViewDescription.Texture2DResource()
            {
                MipLevels = 1,
                MostDetailedMip = 0,
            }
        });
var depthStencilDesc = new DepthStencilStateDescription()
        {
            DepthComparison = Comparison.LessEqual,
            DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All,
            IsDepthEnabled = true,
        };

And here is how I sample the depth in the .fx file:

int3 posTex = int3(input.p.xy, 0);
float depthPixel = DepthTexture.Load(posTex);
float4 color = float4(depthPixel, depthPixel , depthPixel, 1.0f );
return color;

And here the way I'm now setting the Depth Buffer stencil view as a Render Target in 2 passes. In the first I try to set the depthstencilview as a target. In the second pass I'm trying to set teh depth texture as a shader resource to read from it.

this.device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0));

// PASS 0
this.device.ImmediateContext.OutputMerger.SetTargets(depthBufferStencilView);
this.device.ImmediateContext.ClearDepthStencilView(this.depthBufferStencilView,     DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
this.technique.GetPassByIndex(0).Apply(this.device.ImmediateContext);
this.device.ImmediateContext.DrawIndexed(this.geometry.Indices.Length, 0, 0);

// PASS 1
this.device.ImmediateContext.OutputMerger.ResetTargets(); // unbinding the depthStencilView

this.device.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, LinesVertex.SizeInBytes, 0));
this.depthStencilShaderResourceVariable = effect.GetVariableByName("DepthTexture").AsShaderResource();
this.depthStencilShaderResourceVariable.SetResource(this.depthBufferShaderResourceView);
this.technique.GetPassByIndex(1).Apply(this.device.ImmediateContext);
this.device.ImmediateContext.DrawIndexed(this.geometry.Indices.Length, 0, 0);

Finally, this is how I set the two passes in the .fx file:

technique11 RenderMyTechnique
{
pass P0
{

SetDepthStencilState( DSSDepthLessEqual, 0 );
SetVertexShader     ( CompileShader( vs_4_0, VShader() ) );
    SetHullShader       ( NULL );
    SetDomainShader     ( NULL );
    SetGeometryShader   ( NULL  );
SetPixelShader      ( NULL );
}

pass P1
{
SetDepthStencilState( DSSDepthLessEqual, 0 );
SetVertexShader     ( CompileShader( vs_4_0, VShader() ) );
    SetHullShader       ( NULL );
    SetDomainShader     ( NULL );
    SetGeometryShader   ( CompileShader( gs_4_0, GShader() ) );
SetPixelShader      ( CompileShader( ps_4_0, PShader() ) );
}
}


texts: Need help in determing what, if any, tools can be used to create a free Flash game

texts:
Yes I proudly -and sadly- declare that I am a complete nincompoop when it comes to Flash, and I have been fishing around the big wide web for information. The reason for this is that I have been contracted to create a game(s) for a website -the usual flash-based games caveat. Please I do not mean things like by those gaming generator websites, I mean small yet professional games- but the caveat, as always, is that impossible dream: it needs to be done all for free. The budget...well imagine it as not there.

Annoyingly is that I am a game designer yes, but with a ridiculously tight deadline I haven't got much time to re-learn (ah the heady days of programming at uni) everything by the end of March, so I'd like to ask some people who know their stuff rather than keep looking at a gazillion different things.

This is my understanding: with the flash sdk you can create a game, albeit you need to be pretty programming savvy. FlashDevelop helps there -yet I am not entirely sure how. Yet even FD says to use Flash for the animation/graphics.

Yes its undeniably powerful but as I said there is the unattainable demand of no money. The million dollar question: what, if any, tools can I use to create a free flash game?


texts: 2D open world MMORPG; big map memory problem

texts:
I am developing an 2d open world mmorpg game for learning purposes, and have a issue with big maps.
A year ago i developed 2d open world single player / co-op game. It saved map in chunks, and AI for NPCs starts 'ticking' when specified map chunk is loaded.
In my mmorpg game, NPCs AI is handled by server, and its always 'ticking' in some specified interval. That is where my troubles begin. I want NPC to walk in random directions. For this to work, I have to check map collision for every step, so my NPC wouldn't end up in wall. Problem is when I have big map, for example 10000x10000, and every tile is represented with 6 bytes, that is about 572MB of map data my server must hold in memory all the time, and i cant load just few map chunks, like in my single player RPG because of lot NPCs AI needs to be updated all the time, even if player is not located near by.
My goal is to archive map size of 50000x50000 tiles. I know its possible because i seen 2d mmorpgs with huge open worlds, a lot bigger then 50000x50000, and I doubt that their server have 20GB of ram to waste just on maps.
If anyone have any ideas how I can lower memory usage, I woud like to hear you.

Thanks in advance, and sorry for my bad english


texts: How can I generate roads such as those in the game Twisty Road?

texts:
Here is a link to see the gameplay: https://www.youtube.com/watch?v=03PzsgO-uAM
How could I procedurally generate the path upon which the ball rolls in Unity/C#?
I know I could model distinct pieces of the road in Blender and import them into Unity as prefabs. My problem is, I genuinely have no idea where to start when it comes to programmatically generating the whole road out of those prefab sections in a cohesive manner, such that the road is built seamlessly and randomly with twists and turns in three-dimensional space.
I would appreciate any insight you could provide. Thank you.


texts:
Take a look at Super Mario, or even PacMan, or Arkanoid.

How are their levels made, do they created a simple level editors to visualize them, or they designed them by hand (directly with code)?