texts: How do I blink a sprite a few times before it disappears?

texts:
I need the 3d poop emoji model in the chest on the right to blink, visible-invisible-visible, several times:

This is a 3d gameObject oriented to face the camera, shaded with an unlit material.

I need the object to "blink/flash" to indicate that the item has been obtained. The object needs to be generated the moment the lid opens (done), stay unchanged until the lid pops all the way up (0.2 seconds), and flash 3 times during the 0.6 seconds the lid is up. The object is destroyed the moment the lid starts to come down again.

My code (blinking/flashing is not working)

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

public class ItemBox : MonoBehaviour
{

    bool disabled = false;
    private Animator anim;
    public GameObject item = null;

    void Start()
    {
        anim = GetComponent<Animator>();
        if (!disabled)
        {
            anim.Play("ItemBoxIdleState");
        }
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter (Collider other)
    {
        if (!disabled && other.gameObject.tag == "Player")
        {
            anim.Play("ItemBoxGetItemState");
            GameObject itemClone = Instantiate(item, transform.position + new Vector3(0, 0.5f, 0), Camera.main.transform.rotation * Quaternion.Euler(0,180,0));
            Blink(itemClone);
            Destroy(itemClone);
            disabled = true;
        }
    }

    IEnumerator Blink(GameObject obj)
    {
        Renderer objRenderer = obj.GetComponent<Renderer>();
        objRenderer.enabled = true;
        yield return new WaitForSeconds(0.2f);

        for (int i = 0; i < 3; i++)
        {
            objRenderer.enabled = false;
            yield return new WaitForSeconds(0.1f);
            objRenderer.enabled = true;
            yield return new WaitForSeconds(0.1f);
        }
    }
}

Instead of blinking/flashing, the object is just there, doing nothing.


texts: curve objects in unity3d to wrap around an invisible cylinder?

texts: Is there a way to transform objects in unity3d so that they can become curved? Imagine that I wanted to create a rectangle that wraps around an invisible cylinder, or that I wanted take a sprite image and roll it up like a roll of paper. Do you know how this would be done?


texts: How are profiling- and tracing -techniques used in Game Development?

texts:
I feel that in order to create realistic real-life games, game developers need some ways to monitor the system itself i.e. players' moves, other events and the state of the system itself. I know that creation of profiling/tracing -systems is not that easy, look how many people have tried to do better coverage -program in Python and fell far away from the original coverage.py.

I may be associating profiling/tracing wrongly to this game-development phase of dynamic monitoring but I am interested to know where/how profiling and tracing -techniques such as pythonic sys.settrace() are used in game development?
What is their purpose and what are the dynamic event monitoring systems really called? Game engines?
Are there some ready systems to advance/investigate profiling/tracing -areas in game development?


texts: How does Blizzard manage to support Mac OS and Windows in their games?

texts:
I've always thought that using Direct X for Windows was the most powerful, easy and modern method to create games with modern graphics, nowadays. Knowing that it's only Windows, I thinks it's pretty difficult to make something similar on other platforms; Mac OS, to be exact. However, Blizzard somehow managed to deliver Starcraft 2 for Mac OS, and Diablo 3 will be available for Mac, too.

So what I'm interested in is information about:

what technologies are they using for their game engines?
are they using one engine for both games (Starcraft 2 and Diablo 3), or do they develop custom engines for each game?
what are they paying, in terms of time and money, for Mac OS support?


texts: How to project textures onto an animated model?

texts:
I'm trying to figure out exactly how to project textures onto an animated  model. I've taken a look at L4D2's wound's white paper. But their method doesn't exactly explain how they went about this.

I've tried using the old school method to create a mesh and attach it to the object... But that would require the GPU to store that data for a long period of time, and recall it correctly for the animated model. On top of that there's the Z-fighting problem with it.

I've tried the Deferred shading method. But I can't get that to work correctly either. My set up requires some form of filter in order to prevent the decal from projecting onto other models. And then should a moving body part cross over the volume, it gets rendered onto that as well, which is not as desired.


texts: How does this background scrolling code work?

texts:
I'm glad that this code does exactly what I wanted it to do...But I can't make sense of it although I wrote it from scratch myself.  What I wanted to do was create an infinitely scrolling background.

What I figured I'd need to do was have it draw the entire background twice so that the second one comes in after the first one, and when the first one gets to the end it starts over behind the second one, and it would loop like this forever.  However, after I wrote the code to make it scroll and tested it, it scrolls infinitely by just having the code draw the background once...

I have the function to draw the background like so...

void drawBackground(int xStart,int yStart,SDL_Rect *clip) {
  int x,y;
  for(y=yStart;y<SCREENH;y=y+TILEH) {
    for(x=xStart;x<SCREENW;x=x+TILEW) {
      drawClip(x,y,background,&clip[45]);
    }
  }
}

And then I use the function like this to scroll the background...

bgX -= 1;
if(bgX==SCREENW) bgX=0;
bgY -= 1;
if(bgY==SCREENH) bgY=0;

drawBackground(bgX, bgY, bgClip);

It works perfectly...I just don't understand what makes it loop around with no gaps.


texts:
I'm working on skeletal animation and so far I've got the skeleton drawn with interpolated animation working (just on the cpu still). I was thinking about changing my file format for my skeleton and animations to have fully calculated matrices stored.

Right now I calculate my matrices recursively by multiplying the parent's world matrix(absolute matrix) by the childs joint matrix, same thing with each frame of animation. I think it would be a good idea to just export all of this pre-calculated to my model format so I could just send these matrices to the shader for skinning.

Is there any reason I should not do this?

Edit: Calculating the matrices is negligible by itself on a rather small skeleton anyway but is there any reason I should calculate them at run time or just pre-calculate in my file format?  I think this sums up my question better.


texts: Should the game host be the authority, or another dumb client?

texts:
When designing a networked multiplayer-game where one player hosts and others connect, there are two strategies I'm aware of:

Have the host-player's game be the authority, with all other players as dumb-clients trying to catch up with the current game-state.  In the code, there will have to be lots of special cases, depending on if the current player is the host or not.
Make the host a dumb-client like everyone else by running a hidden dedicated server on another thread.  The dedicated-server will be the authority, and the host will connect to it like everyone else (through localhost).

What are the advantages/disadvantages of each of these?  Which is used most often (or does it vary by game type/size)?


texts: Function to draw an image inside a rectangle

texts:
How can I draw an image inside a rectangle?

I am introducing myself in the manipulation of images for games, I have a window and inside there is a rectangle that deforms. I would like to fill the rectangle with an image, but I have no idea how to translate the coordinates of the image to the rectangle.
I don't want a library function, I want to implement it myself.

the idea would be to have a function:

void fill_image_rectangle (img, b1, b2, b3, b4) {

// *
}

I use Java on Windows 7 CPU


texts: how to track point on object with rotation

texts:
I'm working on a top down shooter in C++ and need to have a fire point on the player and npc's so that when they rotate bullets come out of the fire point and not the actual position

here's what i mean(red is the fire point):


texts: How to create a countdown timer that shows hours, minutes and seconds in unity?

texts:
Kind of an easy question but everything I have found on this topic is either outdated or only counts down numbers and not time which is what I need. How can I go about creating a countdown timer where I can input a public float or int for time and then the text on screen will count it down to zero in a time format (00:00:00).

For example if I input "120" (or whatever the proper way to input time is) for instance, then the countdown timer would format correctly to "02:00" then start counting down by seconds. The tutorials ive seen just count down by numbers and dont take time into account (120,119,118, etc)

On top of that I am confused on how to implement a way to activate scripts at a certain time, for example at "1:00" left I would like to send a warning message or something. Please help and thanks!


texts: Actor and Sprite, who should own these properties?

texts:
I'm writing sort of a 2D game engine for making the process of creating games easier. It has two classes, Actor and Sprite. Actor is used for interactive elements (the player, enemies, bullets, a menu, an invisible instance that controls score, etc) and Sprite is used for animated (or not) images with transparency (or not).

The actor may have an assigned sprite that represents it on the screen, which may change during the game. E.g. in a top-down action game you may have an actor with a sprite of a little guy that changes when attacking, walking, and facing different directions, etc.

Currently the actor has x and y properties (its coordinates in the screen), while the sprite has an index property (the number of the frame currently being shown by the sprite).
Since the sprite doesn't know which actor it belongs to (or if it belongs to an actor at all), the actor must pass its x and y coordinates when drawing the sprite.
Also, since a actors may reset its sprite each frame (and usually do), the sprite's index property must be passed from the old to the new sprite like so (pseudocode):

function change_sprite(new_sprite)
    old_index = my.sprite.index
    my.sprite = new_sprite()
    my.sprite.index = old_index % my.sprite.frames
end

I always thought this was kind of cumbersome, but it never was a big problem.

Now I decided to add support for more properties. Namely a property to draw the sprite rotated, a property to draw it flipped, it a property draw it stretched, etc. These should probably belong to the sprite and not the actor, but if they do, the actor would have to pass them from the old to the new sprite each time it changes... On the other hand, if they belonged to the actor, the actor would have to pass each property to the sprite when drawing it (since the sprite doesn't know which actor it belongs to, and it shouldn't, since sprites aren't just meant to be used by actors, really). Another option I thought of would be having an extra class that owns all these properties (plus index, x and y) and links an actor with a sprite, but that doesn't come without drawbacks.

So, what should I do with all these properties?


texts: Collision detection in Arkanoid-like game at intersections

texts:
I'm creating an Arkanoid-like game from scratch. I have no (formal or informal) education of any kind in game-development, so I kinda made up things as I went regarding collision detection based on personal ideas of "how it probably works".

I approximate the ball as a point and ignore its thickness, which is small anyway. I compensate for this visually by very slightly making all objects smaller than they are.

I don't "detect" collision, but anticipate it and change the outcome of the next frame. For example:

The ball is currently in position A, and it "wants" to go to E (red line). But I calculate all intersections with all segments which make up the bricks: B, C, D. The closest one to starting point (A) is B, so I choose B as the "real" intersection. I destroy the brick this segment belongs to.

Now I check how would the ball proceed if it would start at B, with its vector flipped horizontally (because I determine that the segment it hit was horizontal). This is the blue line. Again, from F and G, I pick F. I destroy the brick this segment belongs to.

Lastly, the orange line doesn't intersect, so I determine that the bottom of the orange line is where I should place the ball in the next frame.

This worked fine and I was satisfied with it, until I started nailing the edge case of the ball hitting the T intersection, where it all goes bananas.

What should happen here is that the ball bounces to the left and destroys either of the bricks. But what can happen is that my algorithms decides to choose the middle vertical segment (connecting boxes 1 and 2) as the collision point, either belonging to the 1st or 2nd box.

I thought of ignoring the edges of the segments, but then the ball would pass right through the T-intersection in this scenario, because it would also ignore what it's supposed to hit.

You can see it in action here (around after 00:07 mark): https://www.mp4upload.com/p6966u6kuzad

What are common techniques for handling this case? Even if I introduce the width to the ball, it could still hit the exact T-intersection at the tangent, so the problem would remain.

Requested to post code. Here's the main bit. Please note that I'm not expecting you to (or looking for) debugging the application. I'm more asking about how are these things even handled in general.

export function bounceBall(
  ball: Point,
  vx: number,
  vy: number,
  obstacles: Obstacle[],
) {
  const projectedNextPoint = ball.clone().translate(vx, vy)
  const movement = new Segment(ball, projectedNextPoint)

  const touchedObstacles: Obstacle[] = []

  let loop = 10

  let hasCollision = false
  do {
    hasCollision = false

    if (loop-- < 0) {
      throw new Error('oops')
    }

    // If in the previous loop the ball just grazed the surface
    if (movement.isZeroLength()) break

    const collisions: Collision[] = []
    for (const obstacle of obstacles) {
      const collision = getIntersectionOfSegmentAndObstacle_ClosestToStartExcludingStart(movement, obstacle)
      if (collision != null) collisions.push(collision)
    }

    const collision = getClosestCollisionExcludingSelf(movement.start, collisions)

    // We don't count a collision if it's the starting point.
    // If we did, grazing a surface would turn into an infinite loop.
    if (collision == null || Point.AreEqual(collision.point, movement.start)) {
      hasCollision = false
    } else {
      hasCollision = true
      touchedObstacles.push(collision.obstacle)
    }

    if (hasCollision) {
      movement.setStart(collision!.point)
      if (collision!.segment.isVertical()) {
        movement.mirrorVerticallyWrtStart()
        vx = -vx
      }
      if (collision!.segment.isHorizontal()) {
        movement.mirrorHorizontallyWrtStart()
        vy = -vy
      }
    }

  } while (hasCollision)

  return {
    touchedObstacles,
    vx,
    vy,
    newBall: movement.end,
  }
}


texts: I'm creating a path-finder for navmesh. I'm wondering which method should I use after the A* has been completed, funneling or string pulling? What are the advantages/disadvantages of using them on a triangle-based navmesh?


texts: General directions on developing a server side control system for JS/Canvas Action RPG

texts:
Well, yesterday I asked on anti-cheat JS, and confirmed what I kind of already knew that it's just not possible.

Now I wanna measure roughly how hard it is to implement a server side checking that is agnostic to client input, that does not mess with the game experience so much.

I don't wanna waste to much resource on this matter, since it's going to be initially a single player game, that I may or would like to introduce some kind of ranking, trading system later on. I'd rather deliver better more cool game features instead.

I don't wanna have to guarantee super fast server response to keep the game going lag free. I'd rather go with more loose discrete control of key variables and instances. Like store user's action on a fifo buffer on the client, and push that actions to the server gradually.

I'd love to see a elegant, generic solution that I could plug into my client game logic root (not having to scatter treatments everywhere in my client js) - and have few classes on Node.js server that could handle that - without having to mirror/describe all of my game entities a second time on the server.


texts:
What is the effort required to use a game engine such as Unreal or Unity, etc. and create an avatar customization features...complete with clothes.

The user should be able to customize the body features and the clothes need to then fit onto the customized body.

What is needed?
Can you create one set of 3D models for clothes and somehow programatically have the clothes adapt to the body shape?  I.e. The same shirt model will be able to fit on a skinny person vs. someone with a big beer belly.

How difficult is this? What are the steps needed to implement this avatar creation/dressing feature.

I'm basically talking about something like in Rockband 3.


texts: Real-time UDP multiplayer games: ping measurement?

texts:
In real-time multiplayer games that use UDP for the actual game (CS:S, UT, etc.), how is network latency (ping) measured? More specifically, how do you find out how long ago a UDP packet was sent?

Sorry if this is a dumb question, but I'm very new to network programming.


texts: Overriding all object inspectors in Unity

texts:
How can this be done? I want to add a single label to every component( including non-misbehavior ones ) in the inspector. I've tried:

[CustomEditor( typeof( Object ) )]

And:

[CustomEditor( typeof( Component ) )]

This seems to work for all components that don't seem to have a custom editor already( like BoxCollider, and Transform ). It seems if a component has a custom editor already, it ignores the one I've defined. Even if I change the attribute to this:

[CustomEditor( typeof( Transform ) )]

There is still no change to the Transform inspector. How can I define my own custom editor for these components?


texts:
I am getting the error "AttributeError: 'Rect' object has no attribute 'draw'" with this code:

import pygame
import sys

def terminate():
    pygame.quit()
    sys.exit()

pygame.init()

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
fps=30

screen_height = 520
screen_width = 650
screen = pygame.display.set_mode((screen_width,screen_height))

class Rect(pygame.sprite.Sprite):
    def __init__(self,width,height,color,value):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.value = value
    def change_value(self,color,value):
        self.image.fill(color)
        self.value=value

rects = pygame.sprite.Group()

rect = Rect(100,100,black,1)
rects.add(rect)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            terminate()

    screen.fill(white)
    rect.draw(screen)

    pygame.display.flip()

    clock.tick(fps)

Why is this?  How do I render a rectangle?

I am trying to render and save 8 rectangles which are clickable to turn them on or off. I am trying to render the rects as objects to later use their collision for mouse clicks.


texts:
I'm having some trouble checking if one faction is hostile to another faction in my RPG. I'm using enums for my factions and relations but I feel like there's a better way to approach this.
Currently this is my code for the factions (copy+paste ruined format...)

public enum Faction {
/*
 * Position 1 = Humans
 * Position 2 = Elves
 * Position 3 = Dwarves
 * Position 4 = Orcs
 * Position 5 = Undead
 * Position 6 = Trolls
 * ....
 */

Human(Relations.Friendly/*Humans*/, Relations.Neutral/*Elves*/, Relations.Neutral/*Dwarves*/, Relations.Neutral/*Orcs*/, Relations.Hostile/*Undead*/, Relations.Hostile/*Trolls*/),
Elf(Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Neutral, Relations.Hostile, Relations.Hostile),
Dwarf(Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Neutral, Relations.Hostile, Relations.Hostile),
Orc(Relations.Neutral, Relations.Neutral, Relations.Neutral, Relations.Friendly, Relations.Hostile, Relations.Friendly),
Undead(Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Hostile, Relations.Friendly, Relations.Hostile),
Troll(Relations.Hostile, Relations.Hostile, Relations.Hostile,Relations.Friendly, Relations.Hostile, Relations.Friendly);

    Faction(Relations... relation) {

    }

}

enum Relations {
    Hostile(),
    Neutral(),
    Friendly();
}

class FactionHandler {
    public boolean checkIfHostile(Faction faction1, Faction faction2) {
        //How do I check?
    }
}

The lazy way to do this would be to do lots of if/else statements but I want a more clean way to check.

Basically I want it to check faction1's relation with faction2, and return true if they are enemies, and false if they are friends. Feel free to entirely scrap my code if there's a better solution to this problem as this code is mainly just me experimenting.


texts:
I'm trying to implement the a* pathfinding algorithm in my game. I've looked at dozens of tutorials but I can't seem to get it right. My code is below, and It's not working... does anybody see something I'm doing wrong?
Mainly, I followed these tutorials:
Tutorial 1
Tutorial 2

I'm sure you will be able to understand all of the classes/methods I've created. If you can look over this code and just tell me if it looks remotely correct that would be great.

public void highlightPath(Tile start, Tile end)
    {

        AStar astar = new AStar();

        Tile currentTile = start;
        Tile endTile = end;

        start.node.g = 0;
        start.node.h = astar.getHeuristic(start.getCoordinates(), endTile.getCoordinates());

        start.node.parent = null;//for the loop

        astar.openList.add(start);

        while(!astar.openList.isEmpty())
        {
            currentTile = astar.getTileWithLowestF();

            if(currentTile==endTile)
                break;

            astar.openList.remove(currentTile);
            astar.closedList.add(currentTile);

            AdjacentTiles adjacentTiles = getAdjacentTiles2(currentTile);

            //Assign G and H costs:
            adjacentTiles.aboveRight.node.g = 10 + currentTile.node.g;
            adjacentTiles.right.node.g = 14 + currentTile.node.g;
            adjacentTiles.belowRight.node.g = 10 + currentTile.node.g;
            adjacentTiles.below.node.g = 14 + currentTile.node.g;
            adjacentTiles.belowLeft.node.g = 10 + currentTile.node.g;
            adjacentTiles.left.node.g = 14 + currentTile.node.g;
            adjacentTiles.aboveLeft.node.g = 10 + currentTile.node.g;

            ArrayList<Tile> adjacentTilesList = new ArrayList<>();

            adjacentTilesList.add(adjacentTiles.aboveRight);
            adjacentTilesList.add(adjacentTiles.right);
            adjacentTilesList.add(adjacentTiles.aboveRight);
            adjacentTilesList.add(adjacentTiles.belowRight);
            adjacentTilesList.add(adjacentTiles.below);
            adjacentTilesList.add(adjacentTiles.belowLeft);
            adjacentTilesList.add(adjacentTiles.left);
            adjacentTilesList.add(adjacentTiles.aboveLeft);

            for(Tile t:adjacentTilesList)
            {
                t.node.h = astar.getHeuristic(t.getCoordinates(), endTile.getCoordinates());
            }

            for(Tile t:adjacentTilesList)
            {
               //Check traversability:
               if(t.exists == false)//Change this to test segments/elevation
                   continue;//skips everything below...

               if(astar.closedList.contains(t) && currentTile.node.g < t.node.g)
               {
                   t.node.g = currentTile.node.g;
                   t.node.parent = currentTile;
               }
               else if(astar.openList.contains(t) && currentTile.node.g < t.node.g)
               {
                   t.node.g = currentTile.node.g;
                   t.node.parent = currentTile;
               }
               else
               {
                   astar.openList.add(t);
               }

            }

        }

        Tile startingTile = start;
        Tile currentTile2 = endTile;
        ArrayList<Tile> path = new ArrayList<>();
        path.add(currentTile2);

        while(currentTile2 != start)
        {
            path.add(currentTile2.node.parent);
            currentTile2 = currentTile2.node.parent;
        }

        for(Tile t:path)
        {
            t.highlight();
        }

    }


texts: Environment mapping without cubemap (need coordinates projection)

texts:
I'm working on a project with C++ and glsl (4.1).
I have implemented a mirror object which is a plane at height 0 that works as follow:

I render the scene with a MVP computed such that the camera position is inversed (cam.x, cam.y, -cam.z)
I store the rendered scene as a texture in a framebuffer
I render the scene with a normal MVP
I render the mirror object with the fragment color computed as: (size being the size of the texture I rendered to the framebuffer)

float _u = gl_FragCoord.x;
float _v = gl_FragCoord.y;
_u = _u / size.x;
_v = 1 - (_v / size.y);
_uv = vec2(_u, _v);
reflection = texture(tex_mirror, _uv).rgb;

This implementation works well but I now need to work with a mirror which is not a plane. So I am looking for a way to lookup the same texture I store in the Framebuffer but with the texture coordinates computed from the reflected vector (i.e. find the _uv coordinates from R = reflect(view_dir, vertex_normal)).
Is it possible ? Or is there another way to do this lookup without having to compute a environment cubemap (which is way too costly since my environment is dynamic and I would have to compute 6 textures at each frame)

I have tried this but it doesn't work at all (though I think it should work):

vec3 v = normalize(view_dir);
vec3 n = vertex_normal;
vec4 R = MVP * vec4(reflect(v, n), 1.0);
R = R/R.w;
vec2 _uv = R.xy;


texts: How to add font assets to a Unity based Android app on runtime?

texts:
I am working on an android app that contains a Unity scene. The unity scene has some TextMeshPro text fields where user can enter information. Users also have the option to select fonts for these text fields.

I want to support a lot of fonts. Right now I add all the font assets in Unity. But these font assets add up to increase the app size a lot.

I am trying to find out if there is a way to download these fonts at runtime as per the user's choice so that the initial app size is small? Is this possible?

I would appreciate any links, tutorials, or help. I've not been able to find any information regarding this so far. Thanks!


texts:
Ok, so It's a mesh of frames (high to low density) around the camera that adjusts the vertices Z by height-map values. But what happens, how does it work outside those frames? Its like the coarsest grid that somehave blends with the most outside clipmap (green in pic) frame? Or anything outside it, is not culled?

Edit: also how do collisions with terrain work, if the height values are calculated in vertex Shader?


texts: Lightweight Simple Fast-Object Collision Detection Algorithm/Logic

texts:
I'm making a game where i need to give my objects collision, but i have many fast small objects and normal collision algorithms (Intersection of shapes and such) do not work, because the position+speed iteration advances the walls and there's never actually an Intersection.

I've reserched on those algorithms for a while but they all seem so unecessary complicated, checking all the wall's lines (being that the wall is a rectangle, 4 lines needed to check for each wall..) and maybe resource-expensive...

So i've started constructing my own (Maybe it already exists but i didnt see it anywhere) collision algorithm based on saving the last position the object was.

Please see the following image:

The idea is demonstrated in frame 1 and 2 of the image. Basicly by checking if there's a wall between the left side of the last rectangle and the right side of the new rectangle, i never skip zones while i check collision, and there's no risk of skipping a wall (so i thought).

This is the (sloppy and half-assed) code of the algorithm:

    private void bounce(GameElement b, Terrain t)
{
    Rectangle tR = t.getRectangle();
    int tRleft = tR.x;
    int tRright = tR.x+tR.width;
    int tRup = tR.y;
    int tRdown = tR.y+tR.height;

    Rectangle bRnow = b.getRectangle();
    int bRnowLeft = bRnow.x;
    int bRnowRight = bRnow.x+bRnow.width;
    int bRnowUp = bRnow.y;
    int bRnowDown = bRnow.y+bRnow.height;

    Rectangle bRlast = b.getRectangleLast();
    int bRlastLeft = bRlast.x;
    int bRlastRight = bRlast.x+bRlast.width;
    int bRlastUp = bRlast.y;
    int bRlastDown = bRlast.y+bRlast.height;

    boolean leftRight = false, rightLeft=false, upDown=false, downUp=false;
    boolean betweenX = false, betweenY = false;

    if(bRnow.x>bRlast.x)leftRight=true;
    if(bRnow.x<bRlast.x)rightLeft=true;
    if(bRnow.y>bRlast.y)upDown=true;
    if(bRnow.y<bRlast.y)downUp=true;

    if(bRlastRight>tRleft && bRlastLeft<tRright) betweenX = true;
    if(bRlastDown>tRup && bRlastUp<tRdown) betweenY=true;

    if(leftRight)
        if((tRleft>bRnowLeft || tRleft>bRlastLeft) && tRleft<bRnowRight && betweenY)
        {
            b.setX(tR.x-bRnow.width - 1);
        }

    if(rightLeft)
        if((tRright<bRnowRight || tRright<bRlastRight) && tRright>bRnowLeft && betweenY)
        {
            b.setX(tR.x+tR.width + 1);
        }

    if(upDown)
        if((tRup>bRnowUp || tRup>bRlastUp) && tRup<bRnowDown && betweenX)
        {
            b.setY(tR.y-bRnow.height - 1);
        }

    if(downUp)
        if((tRdown<bRnowDown || tRdown<bRlastDown) && tRdown>bRnowUp && betweenX)
        {
            b.setY(tR.y+tR.height + 1);
        }
}

Its called bounce because its not really organized atm, i still have to think how to structure the algorithm so it becomes more generalized and pratical (Would appreciate help on that too)

This way of doing collision has one bug at the moment which is seen in image 3 (sorry for drawing circles, they are supposed to be squares) because FAST objects still pass diagonals :/ On the other hand, direct hits on walls are pretty neat.

How could i improve, optimize and organize this algorithm? Or is there any better algorithm and im just thinking too much for nothing?


texts: How does a minecraft biome finder generates map

texts:
How does chunkbase biome finder generates map base on seed?
I was curious if chunkbase knows the secret formula for generating the map? Or it uses other math formulas such as scaling, mapping etc...

Here's my main point:
If I generate a map in minecraft and grab that minecraft seed. If I place that minecraft seed in biome finder, It also generates the same world that minecraft generated. If I place the coords in that biome finder, it also shows me the correct position in minecraft world.

How can you possibly generate a world similarly to minecraft without knowing the secret formula? Is this possible?

Here is the site https://chunkbase.com/apps/biome-finder

This is my first question and I'm not a real game dev(I just want you to know). If you want me to remove this question, just tell me.


texts: Using spherical harmonics to build complex sound scapes

texts:
I was having a discussion at work today on how to improve room acoustic modelling.  It was suggested that very little work appears to have been done on the subject yet tonnes has been done in graphics.  It was further suggested that as sound and light are just wave forms it might be possible to use things like ray tracing and radios to get a good approximation.

At this point I began thinking about spherical harmonics to simulate this behaviour.  You could simultaneously do specular-esque reflections as well as audio scattering modelled as diffuse reflections.  As a bonus you'd also get obstructions blocking sound transfer.  The only problem was how to handle the attenuation of multiple frequencies.  Surely though this could be modelled by applying some form of transform to the audio spectrum (FFT).

Anyway does anybody know of any papers on this subject, especially on how it would be performed in real-time.  Failing that anybody got any advice or useful general information?


texts: Straightforward guidelines for converting OpenGL to OpenGL ES?

texts:
Is there a straightforward list of finite steps that I need to follow to convert an OpenGL program into an OpenGL ES that's used on the iPhone and iPad? I'd be using GLKit.

I've seen some similar API functions but I gather that triangles have to be presented differently.


texts:
I have some experience with the Skyrim Creation Kit, and have made some small mods. I am really interested in creating new races, and have already made a mod that allows the player to create an old person, a child or a dremora. To accomplish this, I simply found their IDs in the editor and checked the "playable" box (and unchecked "child"). When I attempt this with some of the non-human races, such as wolf, horse or dragon, the game crashes as soon as I select that race in the character creation screen.

My question is this: Why does the game crash instantly, and is there a way to make animal/monster races playable fairly easily (I don't have much knowledge with scripting or creating meshes). Thanks.


texts: There are tutorials about applying shaders to 3D models, but I would like to know how to use shaders on primitives. I have a world with a lot of vertices and I would like to apply a shader to it without adding any texture to it or loading any model. I'm working with XNA and HSLS.


texts:
I need to find a path with required length in the NxN matrix without loops and deadlocks. For example:

We Have a grid 7x7 (49 blocks in total) with START
(orange) point.

We need to build random path length of 25 cells.

etc

My problem is I don't know how to create the path with required length fast and avoid loops and deadlocks.


texts: Textures selectively not applying in Unity

texts:
On certain imported objects (fbx) in Unity, upon applying a material, only the base colour of the material is applied, with none of the tiled texture showing. This isn't universal; on a test model only some submeshes didn't show the texture, while some did. I have tried every combination of import/calculate normals/tangents to no avail.

FYI I'm not exactly experienced with the software or gamedev in general; this is to make a small static scene with 3-4 objects max. One model tested was created in 3DSMax, the other in Blender. I've had this happen on every export from Blender, but only some submeshes from the 3DSMax model (internet sourced to test the problem)


texts: Applying "zoom to the exact point" transformations to screen positions

texts:
I´ve implemented zooming of orthographic camera (just scaling it with its speed value):

viewMatrix = glm::scale(viewMatrix, glm::vec3(_cameraScale, _cameraScale, 1.0f));

And then applied these transformations (also translation by camera position) to the destination point (actually a cursor position vector) so I got its world positions:

void Camera::applyTransformationsToPoint(glm::vec3& pos) {

    pos += _cameraPosition;

    pos /= _cameraScale;
}

It worked fine, i was getting the right world position with diferent scales.
However, this was done with normal scaling - to the origin of the matrix so basically when i scaled the matrix the whole camera moved to its origin and it looked a little bit weird. SO i have decided to imlement zoom to the middle of the screen feature. So basically what I do is (in pseudocode):

translate(screenWidth/2,screenHeight/2);
scaleTranslatedMatrix();
translate(-screenWidth/2,-screenHeight/2);

It works fine but the code above for transformation of screen coordinations to the world is now not working properly(im not getting the right world positions), any suggestions how to correct it? Thanks.

Edit1:
This is how I apply the scaling (if anyone wondered):

void Camera::zoomOut(float dt) {

    _cameraScale -= _scaleSpeed * dt;

    if (_cameraScale < 0.4f) {

        _cameraScale = 0.4f;
    }
}

According to the first answer edit:
As I have 4x4 matrix and using a vec3 for my point representation, i have to use temporary vec4 to perform the multiplication, however, it is not working correctly (even without scaling and just translating the view matrix) - for inverse matrix im using GLM library.

glm::vec3 Camera::applyTransformationsToPoint(glm::vec3 pos) {

    glm::vec4 tmpVec(pos.x, pos.y, pos.z, 1.0f);
    tmpVec = tmpVec * glm::inverse(viewMatrix);

    return glm::vec3(tmpVec.x,tmpVec.y,tmpVec.z);
}


texts: How to run in any direction while looking and shooting at the enemy

texts: In Bayonetta, you can run in any direction and keep shooting at your target and looking at it while locked on. How did they do that animation? I want to implement it using Unity.


texts: Collision on the first rectangle only - Why?

texts:
I've made a very simple collision detection, it works fine. However, when I decided to load in all my rectangles into a list and then give each of them collision, it only adds it to the first one. Any ideas? I've tried it with a for loop as well.

Here's the code:

    Rectangle interaction, interaction2, interaction3;

    List<Rectangle> collisionList = new List<Rectangle>();

        public GamePlayScreen()
            {

                interaction = new Rectangle(200, 200, 32, 32);
                interaction2 = new Rectangle(400, 200, 32, 32);
                interaction3 = new Rectangle(200, 400, 32, 32);

                collisionList.Add(interaction);
                collisionList.Add(interaction2);
                collisionList.Add(interaction3);

            }
    // This right here is just to show you guys that it is getting updated.
    // This is not the real update, I refrained from posting that since it might confuse
    // people.
    public override Update(GameTime gameTime)
    {
    CheckCollision();
        }

     float xx;
     float yy;

        private void

CheckCollision()
            {
                foreach (Rectangle rect in collisionList)
                {
                if (player.Sprite.Bounds.Y > rect.Top - 33 && player.Sprite.Bounds.Y < rect.Bottom && player.Sprite.Bounds.X < rect.Right && player.Sprite.Bounds.X > rect.Left - 30)
                {
                    player.Sprite.position.Y = yy;
                }
                if (player.Sprite.Bounds.Y < rect.Bottom && player.Sprite.Bounds.Y > rect.Top && player.Sprite.Bounds.X < rect.Right && player.Sprite.Bounds.X > rect.Left - 30)
                {
                    player.Sprite.position.Y = yy;
                }
                if (player.Sprite.Bounds.X > rect.Left - 30 && player.Sprite.Bounds.X < rect.Right && player.Sprite.Bounds.Y > rect.Top - 30 && player.Sprite.Bounds.Y < rect.Bottom)
                {
                    player.Sprite.position.X = xx;
                }
                else
                {
                    xx = player.Sprite.position.X;
                    yy = player.Sprite.position.Y;
                }
                }

            }

    //The Draw method

    spriteBatch.Draw(scrollDownButtonNormal, interaction, Color.White);
                spriteBatch.Draw(scrollDownButtonNormal, interaction2, Color.White);
                spriteBatch.Draw(scrollDownButtonNormal, interaction3, Color.White);

I will of course continue to work on this, and post a solution if I find one.

~Etarnalazure

UPDATE
Just checked with a boolean if the other boxes react, it changes to true. So it means it works just fine (I put the boolean in between each if loop to check if it registered any collision).


texts: Blender 2.6: How to Merge the Pros of Meshes and Surfaces

texts:
there are two interesting kinds of objects: Meshes and Surfaces. Each of them offers very cool features.

Object Type Specific Features

Nice Features of Surfaces:

(for example)

They're as scalable as vector graphics (really nice!)
You can build winding things real simply.

Nice Features of Meshes:

(for example)

You can build organic things really good using the Sculpt Mode and a graphic tablet.
You can use some special things like Physics.

My Question

There are things for which Surfaces are better and things for which Meshes are better. But how can I use both the best features of Surfaces and the best features of Meshes on one object at once?

For example: How can I use Physics (like on Meshes) on lossless scalable objects (like Surfaces)?

Thanks.


texts:
Old games use Distance Fog to limit the draw distance and decrease the number of polygons drawn.

This is usually done by lerping the color to the fog color.
But what if this color is full transparency and the resulting color is alphablended with the underlying image?
Is Alpha blending in this case more performance heavy?

I am talking about an effect like this:


texts: Using gluLookAt to move camera in 2D iPhone game?

texts:
I'm trying to use gluLookAt to move the camera in my iPhone game, but every time I've tried to use gluLookAt my screen just goes "blank" ( grey in this case )

I'm trying to render a simple triangle and to move the camera, this is my code:

to setup my scene I do:

glViewport(0, 0, backingWidth, backingHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glRotatef(-90.0, 0.0, 0.0, 1.0); //using iPhone in horizontal mode
glOrthof(-240, 240, -160, 160, -1, 1);
glMatrixMode(GL_MODELVIEW);

then my "triangle rendering" code looks like:

GLfloat  triangle[] = {0, 100, 100, 0, -100, 0,};
glClearColor(0.7, 0.7, 0.7, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glColor4f(1.0, 0.0, 0.0, 1.0);
glVertexPointer(2, GL_FLOAT, 0, &triangle);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);

This draws a red triangle in the middle of the screen, when I try to apply gluLookAt ( I got the implementation of the function from Cocos2D so I asume it's correct ), i do:

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,0,1,0,0,0,0,0,1); // try to move the camera a bit ?

GLfloat  triangle[] = {0, 100, 100, 0, -100, 0,};
glClearColor(0.7, 0.7, 0.7, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glColor4f(1.0, 0.0, 0.0, 1.0);
glVertexPointer(2, GL_FLOAT, 0, &triangle);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableClientState(GL_VERTEX_ARRAY);

This leads me to grey screen (glClearColor is grey), I've tried all sort of things and read what I've found about gluLookAt on the net, but no luck :(, if someone could explain me or show me how to move to move the camera in a top-down fashion ( zelda, etc ), I would really appreciate it.

Thanks!


texts: How to do monster AI movement and attacks server side?

texts:
I have my web based rpg game already created. Inventory management, equipment system, character stats, skill tree, and etc. It's almost complete.

For the game world, I am creating a top-down rpg character movement and combat. With point and click. You click on a part of the map (in this case, it's a image, and your character .png image transitions to that spot). It's with Javascript and PHP. I'm using a PHP Websocket server. I have it where players can only move up to 200 pixels per each click. Each click is essentially a packet being sent to my gameserver. Then the gameserver validates if it's a valid input (1235x1235) format, and spits it out to other players in that specific game. (So it's a consistent world/map). This works perfect.

My question is:  If I want to incorporate a monster that has AI and starts to attack the character... I can do that with javascript easily with setInterval or setTimeout functions (to make the mob move and then attack the character). But how do I do that serverside? Because a user could just press F12 and edit the javascript to stop the mob from attacking. But, I need the mob to attack the player every xxx milliseconds serverside as well. How is this done with PHP? I feel like I need some type of heartbeat going on where it's a constant check between client and server every xxx seconds? I might be going off on the deep end and I'll stop talking lol. But I hope you get the jist of it. Any ideas are greatly appreciated.

Another thought: Think of Diablo 2 or Path of Exile, and using a hack that just stops mobs from moving towards your character and attacking it. Is that just an illusion? And the "auto attacking" is done serverside regardless if you've stopped that mob on the client, right? If so, how to accomplisgh this with a PHP Websocket server, and some JS?  I'm not looking for code, just an application theory or design process would help! :)

P.S. It's either I go this route, or the game becomes a simple real time strategy pokemon style combat. Which I really, really don't want...


texts: Is it bad to store other memory in a system, alongside the components buffer using an Entity-Component-System architecture (ECS)?

texts:
I'm currently writing a simple ECS architecture for an engine and I have the fundamentals in place but after reading up on this architecture, it is designed in such a way that the memory is contiguous for all of the components and systems.

My understanding is that the components should be stored right after each other so they are not somewhat fragmented in memory? So that way when I update all of the components, the cache prefetcher can help out performance by fetching the next lot of components (limited understanding) without jumping around.

class system1 final
{
public:
        //...

private:
    std::vector<component1>         m_components;
};

class system2 final
{
public:
        //...

private:
    std::vector<component2>         m_components;
};

Then in some manager, you would initialize the systems so that they are as close as possible in memory.

But what if I wanted to allocate additional memory in the systems? Like a few extra buffers for dealing with system-specific information. That would then separate the component buffers so they are no longer next to each other.

class system1 final
{
public:
        //...

private:
    std::vector<component1>         m_components;
    std::vector<int>                m_somebuffer;
    std::vector<int>                m_someOtherBuffer;
};

class system2 final
{
public:
        //...

private:
    std::vector<component2>         m_components;
};

Would this cause any problems and does this break the whole ECS
principle?
What should I be considering here for maximum performance without stumbling on issues later?

I don't want to optimize prematurely but knowing what makes an architecture fast and somewhat optimal during development is an interesting topic for me. Any input is greatly appreciated.


texts: How can I avoid redundancies when I have multiple distinct Roblox tools with clientside code?

texts: In Roblox, I have two distinct tools with identical clientside code. The serverside code determines their difference to behave differently. However, with identical clientside code, whenever I change one, I have to change the other, and it's redundant in the game and also tedious. How can I avoid redundancies when I have two nearly identical but distinct tools with identical clientside code? Basically, I have one serverside script to handle the remote events, in ServerScriptService, and two tools, and it happens that they both invoke the same serverscript and are otherwise identical. How can I avoid redundancies?


texts: Unity new Input system lists actions and compare them to current input

texts:
I have a scriptable object called Move that had a list with keycodes (for example to make a Hadouken) easy to use and compare with the current input made it with the old system, but with the new input system I don't know how to make a list of actions (actions that are in my Input Action Asset not new ones) and compare that with the current inputs (and also I do not have any idea how to make buffering inputs like the last input repeats 3 frames).
I already tried and not worked (InputMa is my InputActionAsset generated class):
-InputActions[]
-InputMa[]
-InputMa.PlayerActions
-InputActionReferences[] this seems the correct option, but I don't know how to get the reference from the current input.


texts: How to give node sillouhette when behind wall in Godot

texts: I am working on a boss-rush fps game. I want it to be like the eye of cthulu fight from terraria, with the enemy flying towards you and then turning around to try again if it misses. However, in order for that to work, the enemy must be visible when they are under the ground. How could I accomplish this?


texts: How to edit visual appearance of mod in Euro Truck Simulator 2(ETS2)

texts:
Not sure if this is the right place, so here goes nothing...

I want to update my truck's appearance in-game, to make it more on par with it's real life counterpart. The part of the truck I want to edit, to be more specific, is the grill of the truck. The truck's looks are pretty outdated, and it seems it needs a facelift.

From what I found, all my sources tell me that I need to edit the base files of the game, and then I can alter the game mod itself. Is there a simpler way of updating the truck's appearance? Or am I better of just sticking with it's old looks?


texts: The character does not stand still on the moving platform

texts:
I'm trying to create a simple platforming game. I have an animated platform moving in 2 opposite directions. I use this simple code to make the character move along with the platform while he is standing on it:

public class PlatformMoving : MonoBehaviour
{
    private void OnTriggerEnter(Collider other) => other.transform.parent = transform;

    private void OnTriggerExit(Collider other) => other.transform.parent = null;
}

The character moves with CharacterController.Move(). When he stands still on the platform and movement vector equals to Vector3.zero, he moves in the direction opposite to the platform movement direction and can even fall down from the platform. But if I comment charController.Move(movement) line in a character motion script, everything works properly and the character does not move when he shouldn't do that. How to solve it?


texts:
I'm attempting to write an inventory system(C++, doesn't need to be huge), that later on should be able to be drawn in a GUI.

In the file structure, I think it would be best to put both information about the item itself and references to graphics, etc. in one file.

But how does that translate into code? How should I tell the renderer, for example which sprite to draw for which item and where to do that. Should I only have the CInventory and the CItem class, containing both logic and sprite information, or should I create separate logic and GUI inventory(in this case meaning both CInventory and CItem) classes which are then linked by a common item-id for example?

Answers are always appreciated :)


texts: How to detect when the current animation is finished in code in Unity's Animator?

texts:
I have a model with an animation controller. I set the states and parameters for transitions between them. Now I need to make the model play its animations in the order I want.

I can use:

GetComponent.<Animator>().SetBool("someparameter",true);

to uncheck currently checked parameter and check another parameter after current animation finished.

Please help me to find a way to make a condition "when the current animation finished".

The examples I'm finding are related to animation component (not animator), or they are too complicated for me, while I need a simple way I can understand and use quickly.

Thank you so much in advance!


texts:
Does anyone know how to use "dual vibration feedback makes your games more realistic and immersive." on this logitech gamepad

I know about pygame however I don't think it gives feedback.

http://www.logitech.com/en-us/product/wireless-gamepad-f710


texts:
I've worked with 3DS Max in Uni and am trying to learn Blender.

My problem is I know a lot of simple techniques from 3DS max that I'm having trouble translating into Blender. So my question is:

Say I have a poly in the middle of a mesh and I want to split it in two. Simply adding an edge between two edges. This would cause a two 5gons either side.

It's a simple technique I use every now and then when I want to modify geometry. It's called "Edge connect" in 3DS Max.

In Blender the only edge connect method I can find is to create edge loops, not helpful when aiming at low poly iPhone games.

Is there an equivalent in blender?


texts: I am making a 3rd person game for pc. Space, of course, makes the player jump in game. For some reason if I interact with my menu at all and then press space it will open my menu back up. This doesn't happen if I don't interact with the UI first though. I don't know if this is a bug or what but my code does not contain anything that would take input from the keyboard in general so the space bar interacting with it doesn't make sense. Has anyone seen this issue before?


texts:
I am making an xna game which contains turn-based RPG battle elements. Any good game that features turn-based battle has to have a good feedback to the user.

For example, When my guy attacks, there should be a text popup that says something like "HERO DOES 15 DMG!". And this text should disappear several seconds after.

I am currently able to put text on the screen via standard spritefont drawing. However, in order to make it disappear I am currently using bools and a timer. I have been doing research on timing related stuff but I seem to be very bad at it.

Using some of the suggestions I have received, I have made a messagesystem class. But I am still confused about the implementation. Here is the new code:

public class MessageSystem
    {

        public static readonly MessageSystem Instance = new MessageSystem();
        public float timenow;

        struct Message
        {
            public SpriteFont Font;
            public string Data;
            public Vector2 Position;
            public float Duration;
            public bool isActive { get; set; }

        }

        List<Message> Messages = new List<Message>();

        public MessageSystem()
        {

        }

        public void Show(string data, Vector2 pos, SpriteFont font, float duration)
        {
            Messages.Add(new Message() { Data = data, Font = font, Position = pos, Duration = duration });
        }
        public void Update(GameTime gameTime)
        {
            timenow += (float)gameTime.ElapsedGameTime.TotalSeconds;

            for (int i = 0; i < Messages.Count; )
            {
                if (Messages[i].Duration < timenow)
                {
                    Messages.RemoveAt(i);
                    continue;
                }
                i++;
            }
        }

        public void Draw(SpriteBatch batch)
        {

            foreach (Message msg in Messages)
            {
                batch.DrawString(msg.Font, msg.Data, msg.Position, Color.Lime);
            }

        }

    }

Here is the implementation part:

if (p1atktimer >= 10)
            {
                AttackMsg.Show(playerBattler.Name + " attacks furiously!", battlemsgs, battlefont, 2.0f);
                DealDmgFromLeft(gameTime);
                p1atktimer = 0;
                timenow = 0;
            }

In my update method I just have:

Attackmsg.Update(gameTime);

And similarly, in my Draw method I have:

Attackmsg.Draw(spriteBatch);

So, it goes away when it is supposed to, but it does not appear again when the p1atktimer condition becomes true again. I guess i have to surround the attackmsg.Draw(spriteBatch) command with conditionals instead of the show? But this brings me back to my previous question: Do I have to make bools for everytime I want to show this kind of text.

Let's continue with this example, I am going to make a bool atkmsgshowing = false. And make it true when someone's attackguage reaches 10. Because, if I do not do this, the msg works only once. So then, the attacker attacks, and I will make the bool true. When the attack ends, atkmsgshowing will go back to false. Doesn't this defeat the purpose of making a MessageSystem class?


texts:
I just solved my issue

in my object (on the stage) I forgot to name the element

I'm trying to make workin a custom mouse cursor on my Scaleform menu.
I have follow some tutorials but nothing good...

Right now I have tried the Matt Doyle's AS :

import scaleform.gfx.Extensions;
Extensions.enabled = true;

Mouse.hide();
var mCursor:MovieClip;
mCursor.mouseEnabled = false;
mCursor.tabEnabled = false;

function handleMouseMove( e:MouseEvent ):void
{
    mCursor.x = e.stageX;
    mCursor.y = e.stageY;
}

stage.addEventListener( MouseEvent.MOUSE_MOVE, handleMouseMove, false, 0, true );

but i'm little confused on how declare the cursor
should I add it on the stage, or can I use some addChild() to have it on the screen

for information mCursor is also the name of the cursor movieClip in my library


texts: What's the difference between Alpha and PreMulAlpha?

texts: I've seen videos comparing the two but it looks like there's no difference and they don't explain what's the difference


texts:
I would like to simulate a point that moves in 2D. The input should be the speed of the mouse, so the new position will be computed as following

new_position = old_position + delta_time*mouse_velocity

As far as I know in GLUT there is no function to acquire the current speed of the mouse between each frame. What I've done so far to compute the delta_time as following

void Display()
{

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(1.0f, 0.0f, 0.0f);
    static int delta_t, current_t, previous_t;
    current_t = glutGet(GLUT_ELAPSED_TIME);
    delta_t = current_t - previous_t;
    std::cout << delta_t << std::endl;

    previous_t = current_t;
    glutSwapBuffers();
}

Where should I start from here? (Note: I have to get the speed of the mouse because I'm modeling a system)

Edit:
Based on the above code, delta_time fluctuates so much

34
19
2
20
1
20
0
16
1
1
10
21
0
13
1
19
34
0
13
0
6
1
14

Why does this happen?


texts: how to get the current location in the map surface - slick 2D

texts:
@Override
public void mouseMoved(int oldx, int oldy, int newx, int newy) {
  super.mouseMoved(oldx, oldy, newx, newy);
}

we can get the mouse location in this method via newx, newy . i want to know is there any such way to get the location in slick2D? when we press the arrow keys and move a image of a man on the game surface(tile map)?


texts:
How can I do AABB collision engine? What do I need? I need it to do a platformer game (don't want to use box2d etc.).

I tried to make it like this

void GameplayScreen::Update()
{
    ePlayer->Update();
    collision();
}

void GameplayScreen::Draw(SDL_Renderer *renderer)
{
    DrawMap(renderer);
    ePlayer->Draw(renderer);;
}

void GameplayScreen::DrawMap(SDL_Renderer *renderer)
{
    for (int y = 0; y < map.size(); ++y)
        for (int x = 0; x < map[y].size(); ++x)
            if (map[y][x] != 0)
            {
                SDL_Rect destRect;
                SDL_Rect srcRect;

                srcRect.w = 32;
                srcRect.h = 32;
                srcRect.x = blockID * srcRect.w;
                srcRect.y = 0;

                destRect.x = (x * 32);
                destRect.y = (y * 32 );  /
                destRect.w = 32;
                destRect.h = 32;

                vBlock[Earth]->Draw(renderer, srcRect, destRect);
            }
}

void GameplayScreen::Collision()
{
    for(int y = 0; y < map.size(); ++y)
        for(int x = 0; x < map[y].size(); ++X)
            if(map[y][x] != 0)
            {
                int mapX = x * 32;
                int mapY = y * 32;
                int mapW = x * 32 + 32; // I tried (x + 32) * 32 also
                int mapH = y * 32 + 32; // I tried (y + 32) * 32 also

                int playerX = ePlayer->getPosX();
                int playerY = ePlayer->getPosY();
                int playerW = ePlayer->getPosX() + ePlayer->getHitBoxX();
                int playerH = ePlayer->getPosY() + ePlayer->getHitBoxY();

                AABB aabb(mapX, mapY, mapW, mapH);
                if(aabb.chechCollision(playerX, playerY, playerW, playerH))
                {
                    //I don't know what do write here
                    //I wrote what I thought would be good

                    if(playerX <= mapW && playerX >= mapX)
                    {
                        std::cout<<"Player collision Left"<<std::endl;
                    }
                    else if(playerW >= mapX && playerW <= mapW)
                    {
                        std::cout<<"Player collision  right"<<std::endl;
                    }
                    else if(playerY <= mapH && playerH >= mapH)
                    {
                        std::cout<<"Player collision top" <<std::endl;
                    }
                    else if(playerH >= mapY && playerH <= mapH)
                    {
                        std::cout<<"player collision bot"<<std::endl;
                    }
                }
                else std::cout<<"NO COLLISION"<<std::endl;
            }
}

bool AABB::checkCollision(float x1, float y1, float w1, float h1)
{
    if ((x <= w1 && x >= x1)
            && (w >= x1 && w <= w1)
                && ((y <= h1 && h >= h1)
                    || h >= y1 && h <= h1)) // I tried here with &&
    {
        return true;
    }
    return false;
}

The problem with this is that, even if map[y][x] == 0 => no collision.

The game says that there is a collision.


texts: How to align a 3D object with four points?

texts:
I'm sure there's a better way to articulate this question, but I lack the vocabulary.

Imagine a skateboard. As it rolls straight down a road, the "deck" is aligned with the road, just offset a few inches higher.

If the skateboard is on a ramp with an incline of say 20º, then then deck of the skateboard can be aligned with the ramp by rotating along it's x-axis by 20º.

But what if the skateboard approaches the ramp at an angle?

Perhaps a visual explanation might be easier to understand.

If I know the points at the top of each pink/purple pole, and I wanted to place an object in the scene that aligned with those points, like this...

Is there some known method for figuring this out?

I'm using Unity, if that makes a difference?


texts: How should I design an easing class in C++?

texts:
I'm currently struggling to find a good approach for an easing class for my game.

The class holds some easing effects, like elastic-in-out, and should be called by menu buttons, players and enemies to polish my animations a bit.
(think about a cool bouncing button that fades in)..

This is my very basic easing class so far:

class Easing {

protected:
    double currentTime;
    double startTime;
    double endTime;

public:
    virtual double ease(double t) { return 0.0f; }

};

class Easing_ElasticInOut : Easing {

public:
    virtual double ease(double t) override {
        t--;
        return sqrt(1 - t*t);
    };

};

In my menu I've got a bunch of buttons and I'd like to animate them to ease in when they appear.

void EditorMenu::render() {

    if (is_open()) {
         // Easing_ElasticInOut ???
         // Draw a button with circle_radius depending on the easing
    }
}

This render() method gets called all the time.

How would you design these effects? I'm not sure about how to only call them once and let them finish, especially when there are more buttons or things at once, that need to be animated...


texts: How do I achieve one touch one shot for WP7 game?

texts:
I want to be able to have a sprite shoot in a game for WP7.
What I have at the moment is that as long as the shoot button is held down the sprite constantly shoots.
How do I sort it that only one bullet is shot from touching the button and not a stream of bullets is released? I want for the player to be able to shoot another bullet, they must tap the button again. This was taken from a DreamInCode tutorial on how to make an asteroids clone for PC.

foreach (TouchLocation location in TouchPanel.GetState())
        {

            if (shootKeyBounds.Contains((int)location.Position.X,
                                         (int)location.Position.Y))
            {
                FireBullet();

            }

        }

The fire bullet method

private void FireBullet()
    {
        Sprite newBullet = new Sprite(bullet.Texture);

        Vector2 velocity = new Vector2(
            (float)Math.Cos(ship.Rotation - (float)MathHelper.PiOver2),
            (float)Math.Sin(ship.Rotation - (float)MathHelper.PiOver2));

        velocity.Normalize();
        velocity *= 6.0f;

        newBullet.Velocity = velocity;

        newBullet.Position = ship.Position + newBullet.Velocity;
        newBullet.Create();

        bullets.Add(newBullet);
    }


texts:
I'm trying to build 3D solar system with webGL.
I have all the stars moving in a circle around the sun as sholud be, and I want them also to spin around their own Y axis.

How can I add it?
 I tried :

mat4.rotate(mvMatrix, degToRad(starsList[i].Yangle), [1, 0, 0]);

but I got wierd result.
any help?

mat4.identity(mvMatrix);
mat4.translate(mvMatrix, [0, 0, -30]);

for (i = 0; i < starsList.length; i++) {
    mvPushMatrix();
    mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
    mat4.rotate(mvMatrix, degToRad(starsList[i].Yangle), [1, 0, 0]);

    mat4.translate(mvMatrix, starsList[i].initPlace);
    mvPopMatrix();
 }

var lastTime = 0;

function animate() {
    var timeNow = new Date().getTime();
    if (lastTime != 0) {
        var elapsed = timeNow - lastTime;
        for (i = 0; i < starsList.length; i++) {
            starsList[i].angle += starsList[i].speed * elapsed;
            starsList[i].Yangle += starsList[i].speed * elapsed;

        }
    }
    lastTime = timeNow;
}


texts: How to calculate the post Rigidbody2D velocity vector before applying a specific force in Unity?

texts:
I am trying to implement a space rocket in 2D. Whenever the player presses a button, a constant force (Both vertical and horizontal) is being added to that rocket. What I want to add is a maximum speed, the rocket cant exceed as the rocket will continue accelerating to infinity. The player can also choose not to accelerate, which can lead to the rocket starting to fall down due to gravity. Thus, I cant just Clamp the rigidbody.velocity of the rocket whenever the magnitude of it exceeds max speed as it will also limit the fall velocity which is not as limited. Thus, I am trying to predict whether the player will exceed the maximum velocity when trying to accelerate, in order not to add the force.

So far, I have tried doing this but the velocity vector does not seem to change immediately, so vel is equal to postVel:

Vector2 vel = rigidbody.velocity;
rigidbody.AddRelativeForce(Force); // Add force
Vector2 postVel = rigidbody.velocity;
rigidbody.AddRelativeForce(-Force); // Undo force


texts:
As you know there are plenty of solutions when you wand to find the best path in a 2-dimensional environment which leads from point A to point B.

But how do I calculate a path when an object is at point A, and wants to get away from point B, as fast and far as possible?

A bit of background information: My game uses a 2d environment which isn't tile-based but has floating point accuracy. The movement is vector-based. The pathfinding is done by partitioning the game world into rectangles which are walkable or non-walkable and building a graph out of their corners. I already have pathfinding between points working by using Dijkstras algorithm. The use-case for the fleeing algorithm is that in certain situations, actors in my game should perceive another actor as a danger and flee from it.

The trivial solution would be to just move the actor in a vector in the direction which is opposite from the threat until a "safe" distance was reached or the actor reaches a wall where it then covers in fear.

The problem with this approach is that actors will be blocked by small obstacles they could easily get around. As long as moving along the wall wouldn't bring them closer to the threat they could do that, but it would look smarter when they would avoid obstacles in the first place:

Another problem I see is with dead ends in the map geometry. In some situations a being must choose between a path which gets it faster away now but ends in a dead end where it would be trapped, or another path which would mean that it wouldn't get that far away from the danger at first (or even a bit closer) but on the other hand would have a much greater long-term reward in that it would eventually get them much further away. So the short-term reward of getting away fast must be somehow valued against the long-term reward of getting away far.

There is also another rating problem for situations where an actor should accept to move closer to a minor threat to get away from a much larger threat. But completely ignoring all minor threats would be foolish, too (that's why the actor in this graphic goes out of its way to avoid the minor threat in the upper right area):

Are there any standard solutions for this problem?


texts:
I've made a few classes to create soft body objects in libGDX using Box2D (specifically a circle and rectangle similar to these links).

The objects are constructed of a number of circle shaped Box2D bodies (hereafter deform points) connected together by distance joints which allow the object to "deform" when the deform points move around. Collision works more or less fine when the objects are colliding with other standard Box2D rigid bodies such as a box polygon (what they're sitting on):

The problem starts when two soft bodies collide. As you can probably guess from the way they're constructed, the two often pass through each other since the deform points for which Box2D handles collision are small and spaced apart, so they easily don't collide when the two soft bodies should. If the two bodies are placed like seen on the left in the following image, the circle passes through the square, rather than bouncing off the top of it as it should:

I've tried solving the problem (methods shown below) by tessellating the bodies more so that the deform points are closer together (left), which seems far too resource intensive and didn't affect much anyway. Then I tried enlarging the size of the deform points to fill the gaps (middle), which worked perfectly for the collision but as you can see caused problems mapping the texture to the object since the textures don't appear to collide. After that I tried to bound the outside of the object using polygon bodies connected between deform points using revolute joints, this works with the texture better and does prevent objects from falling through each other, but it stops the object from deforming properly.

I can't think of any more ways to tackle this problem, but I'm very new to Box2D and libGDX and maybe I'm overlooking a much more simple solution. I'll give any ideas a shot.


texts: New to video game development and im working in unity on a Mac right now. I also have been using unreal on my pc figuring them both out. Im trying to (in unity) quickly copy prefabs by dragging them to different spots on mac? Basically the unreal engine equivalent to Alt + dragging your actor on windows. I've tried looking it up and shortcuts dont help and randomly pressing buttons and dragging is getting me nowhere fast


texts:
After some rotations and to from quaternion conversions I get negative scale from Matrix 4x4, is it possible? I need that scale to draw sprite on screen so I get sprite flipped,
how to deal with this problem should I just handle negative scale in sprite drawing method.

if MatrixHasNegativeScale  then invert scale, draw sprite with inverted scale
after m4.initWithHeadPitchRoll(0, 0, 180); I already get negative scale.
or something wrong with matrix class?

Edit I create transformation matrix(rotation + scale + translate) rotation around Oz by 180 and when I extract scale from it, it has negative value is it normal?


texts:
I've never played the Wii or Kinect, but to my understanding, the Wii captures user movement with 4 cameras and translates them to controls.

How does this work? Has Nintendo published anything on this? I'd appreciate a mathematical explanation.


texts: How would one program potions that can change virtually every aspect of the character?

texts:
In Witcher 3, there are various potions that the character can consume. There seems to be potions that have various effects during their effect time:

Restores a certain number of health points per time
Instantly restores a certain number of health points
Increases the defense points
If one delivers a critical blow, the damage will be amplified
If one is attached by a vampire and it draws blood, the vampire will become poisoned
Increases the maximum weight capacity by 20 pounds.
Lets you see at night
Improves sight under water and extends the time that the character can hold his breath

Then there are various properties of the equipment that also have various effects (extra 5% experience points, extra attack points, ...) and runes one can put into the equipment.

I can imagine how one could program each of them separately, I do not see how one could program this in a non-intrusive and extensible fashion. It seems the potions must have access to virtually every aspect of the game.

Or is it the other way around? In the attack code, there are hooks for certain potions. In the diving code, there is hook for the one relevant potion.

How does one implement this kind of thing?


texts: Having trouble combining clampMagnitude and some explosion force

texts:
I have a character that uses rigidbody, and I am using AddForce() to make it move. And so I do rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed) to limit diagonal speed. Yes that did worked but my problem is adding for example explosion force. So if explosion force is very high, it will still clamp the velocity of the player. What way should I use to combine movement that limits diagonal speed and a properly working explosion force toward the player. At least give a clue how can I do it?
My only main problem here is the way that I implemented to limit diagonal movement. I wanna improve that by not using Vector3.ClampMagnitude() so the AddExplosionForce() will work properly to the player. Because clamping magnitude of the player will also limit the velocity when it is affected by the explosion force.
So can anyone give a clue how can I implement to limit diagonal movement without using clamp magnitude?
I thought about normalizing the move like:
Vector3 move = transform.right * x + transform.forward * z;
move = move.normalized * Time.deltaTime * moveSpeed;

But I realized I am using AddForce(). Even though I limited the diagonal speed, it will go faster and faster because there is no maxSpeed. Help please.


texts: How to best apply colliders on a rough 3D shape

texts: I have a 3D model for a level in unity. I want to add colliders to it. What is the best type of collider for this model? And,it is 3D


texts: How to demo Advanced Game AI as a portfolio piece?

texts:
Basically every Game company wants to see a portfolio that exhibits your skill set.  If you're specializing in AI though, what and how should you show off your skills.
Some thoughts

Is nice graphics in an AI demo a must(get past nontechnical HR that don't understand AI, think 3d verse 2d)?
Demo multi-featured AI or a single focused example.
Fundamental skills like path-finding, hfsm, planning, etc are critical AI components but does it really impress as a portfolio piece?
Single AI entity, multiple entities, or large populations, is more always better?
Also as a portfolio piece ideally there would be an executable, and videos which should show off whatever is trying to be shown off within only a few minutes.

Examples
I would say any of the skills exhibited in this video would make for a great portfolio piece but are game companies really expecting this from a single person.

Autodesk Kynapse

AI Sandbox is another great example but this was made from the work of many many people.

AI Sandbox

Any examples of good AI portfolios would be great.


texts: UnrealEngine4 "backwards compatilibility": Can I view a site that uses Unreal Engine4 on a very old laptop and still see in high definition?

texts:
Backwards compatible?

The project:

I want to render a high definition model on my personal website such that it'll be rendered in the highest definition possible on any device, from a 20-year-old Gateway PC running Windows 95 to an iPhoneX. It's particularly important that it's real pretty on mobile (whatever Android and iPhone models are big these days)

The question:

I was thinking I'd buy an expensive desktop with GPUs to make sure I can make the app really fancy for users on a high-end desktop with nice monitors. But I'm not going to do that if the high-definition I get on my new expensive screen doesn't make it out to the app my employer is building. How does this work? Does OpenGL display the highest-definition render it can on the mobile device?


texts: TypeError: R[o5R.F6s] is not a function in changing states in phaser box2d

texts:
i build my game using phaser.2.4.3.min.js and phaser.2.2.2.box2d.min.js
When trying to change states this error is being raised TypeError: R[o5R.F6s] is not a function and i can't seem to figure out the problem

PS : i took The source code of box2d plugin from the example folder in phaser , and i did not purchase the full plugin yet i was just testing it .

is there anyway to fix this issue ?

here is the game code : http://jsfiddle.net/fbdtq1tg/5/

and here where the error is raised :

SetGameOver: function () {
            this.game.state.start("TheGame");
        }


texts: How do I make my character slide down high-angled slopes?

texts:
I am currently working on my character's movement in Unity3D. I managed to make him move relatively to the mouse cursor.
I set a slope limit of 45°, which does not allow the character to walk up the mountains with higher degrees. But he can still jump them up.

How do I manage to make him slide down again when he jumped at places with too high slope?

Thanks in advance.

edit: Code snippet of my basic movement.
    using UnityEngine;
    using System.Collections;

public class BasicMovement : MonoBehaviour {
    private float speed;
    private float jumpSpeed;
    private float gravity;
    private float slopeLimit;
    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        PlayerSettings settings = GetComponent<PlayerSettings>();
        speed = settings.GetSpeed();
        jumpSpeed = settings.GetJumpSpeed();
        gravity = settings.GetGravity();
        slopeLimit = settings.GetSlopeLimit();
    }

    void Update() {
        CharacterController controller = GetComponent<CharacterController>();
        controller.slopeLimit = slopeLimit;

        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;

            if (Input.GetButton("Jump")) {
                moveDirection.y = jumpSpeed;
            }

        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}


texts: Is Physics a prerequisite to learn Unity3D

texts: I have got a basic knowledge about the Unity 3D platform but I coding in Unity has not been that easy for me. For the simple reason I can see is, I cannot understand which function to use for what purpose, for example, velocity, angular velocity or torque. My question is do I need to learn Physics and Trignometry to properly learn the usage of functions in Unity script. What level of knowledge should I need to poses with respect to Physics and Trignometry in order to properly understand the code in Unity? Please be specific as I am not a science student and I have really very basic knowledge in Unity.


texts: What is wrong with my Respawn coroutine?

texts:
I am creating a 2D Platformer game in which if the player falls off the base/ground then I want the player to respawn at the nearest checkpoint. However I want there to be a delay between the player falling off the ground and the respawn. This is the section of my code to achieve this goal:

private void OnTriggerEnter2D(Collider2D collision)
{
    Debug.Log(collision.tag);
    if (collision.tag.Equals("Kill"))
    {
        StartCoroutine("Respawn");
    }
    else if(collision.tag.Equals("Checkpoint"))
    {

        Animator flag = collision.GetComponent<Animator>();
        if (!flag.GetBool("hasCrossed"))
        {
            flagCounter++;
            flag.SetBool("hasCrossed", true);
            checkpoint = collision.gameObject.transform.position;
        }
    }
}

IEnumerator Respawn()
{
    yield return new WaitForSeconds(respawnDelay);
    transform.position = checkpoint;

}

This works fine for small respawn delays like 1 or 2 seconds. But on increasing the delay to 5 seconds, the player after appearing at the nearest checkpoint vanishes off in an instant and then after quite a few repetitions the player reappears.

This is for the 2 second time delay

This is for the 5 second time delay

How can I fix this?


texts:
An object - a player or npc or whatever - has a position, direction and speed and such.

Before drawing each frame, we want to compute the current position of each object.

How do you do this?

If you take the elapsed time since last frame, you run the very real risk of the game running at the wrong speed if the frame-rate is very fast and the clock precision poor (as it often is on some platforms).

And how can you incorporate player controls such as the player wanting to go left or right (e.g. in a simple asteroids clone without ship inertia)?


texts:
I am trying to figure out what is the best way to handle persistent changes in game world. Metroidvania games keep track of the player actions within a level, for example "this boss has been defeated", "this power up has been taken", "this button has been pushed", etc. In "Cave Story", some completed actions will change the state of the main village, and some NPCs will have dialog specific to what the player has done, before.

I can think of two different ways to handle this functionality:

Having a copy of the same map, for each state; this sounds resource heavy, and inefficient.
Using some kind of "chapter" definition that allows me to load/initialise each object of the map in regards to the current chapter. For example, multiple versions of the same NPC would exist, on the map, at various locations, with a chapter attribute. The map can start to get messy, and it can be hard to test.

In regards to the second option, different behaviors and the object loading code would look like this:

if (object.currentChapter == currentChapter) {
    object.load()
}

I am using Tiled, and as proposed, it can then be possible to load the object layer corresponding to the current game state or chapter:

loadMap(map, chapter) {
    ...
    createObjects(map, objectLayerName)
}

As an example, in object_chapter_1, the wizard is outside of a laboratory. In object_chapter_2, the wizard is inside of the laboratory, preparing some magic potions.

I can't really figure out what is the best solution, and what techniques can be used to deal with this problem. What are the differant techniques to deal with different world and story states, in metroidvanias?


texts: XNA player/tile collision not working perfectly

texts:
So I've built a map tile engine in XNA, and have been working on the player/tile collision. The method I'm using works well to some extent, but the player will often move through the walls and get stuck and I can't figure out what's going wrong.

Here's my player update loop. You can see I'm creating a motion vector based on player input, creating a new location where the player will move to, then getting the four surrounding tiles and checking each one for an intersect, then cancelling out the motion in that direction if necessary. If a tile is not null, it is assumed impassable.

Can anyone help point out my mistake?

    public override void Update(GameTime gameTime)
    {
        Motion = new Vector2();
        var newPosition = Position;

        //set movement speed
        Speed = 1;
        if (Controls.IsKeyDown(Keys.LeftShift))
        {
            Speed = 2;
        }

        //set movement
        if (Controls.IsKeyDown(Keys.S))
        {
            newPosition.Y += Speed;
            Motion.Y = 1;
        }
        if (Controls.IsKeyDown(Keys.W))
        {
            newPosition.Y -= Speed;
            Motion.Y = -1;
        }
        if (Controls.IsKeyDown(Keys.A))
        {
            newPosition.X -= Speed;
            Motion.X = -1;
        }
        if (Controls.IsKeyDown(Keys.D))
        {
            newPosition.X += Speed;
            Motion.X = 1;
        }

        //normalize speed vector to stop faster diagonal movement
        if (Motion != Vector2.Zero)
            Motion.Normalize();

        //calculate new position
        newPosition += Motion * Speed;
        var newBounds = new Rectangle((int)newPosition.X, (int)newPosition.Y, Width, Height);

        //check for block collision
        if (Motion != Vector2.Zero)
        {
            //get x,y tile index of player position
            var x = GetPlayerTileX();
            var y = GetPlayerTileY();
            //get surrounding 4 blocks
            var left = MapEngine.Layers[1].GetObject(x - 1, y);
            var right = MapEngine.Layers[1].GetObject(x + 1, y);
            var up = MapEngine.Layers[1].GetObject(x, y - 1);
            var down = MapEngine.Layers[1].GetObject(x, y + 1);
            //check for collision in all directions, and cancel motion accordingly
            if (left != null && left.Bounds.Intersects(newBounds))
                Motion.X = 0;
            if (right != null && right.Bounds.Intersects(newBounds))
                Motion.X = 0;
            if (up != null && up.Bounds.Intersects(newBounds))
                Motion.Y = 0;
            if (down != null && down.Bounds.Intersects(newBounds))
                Motion.Y = 0;
        }

        //move the player
        Position += Motion * Speed;

        //stops player leaving the map edge
        LockPlayer();

        //update bounds
        Bounds = new Rectangle((int)Position.X, (int)Position.Y, Width, Height);

        //camera follows player
        Camera.Position = Position;
    }


texts: Is it a good idea to use box2d to control sprite movement in a 2D game?

texts:
I'm trying to use Box2D to control sprite movement.Some burning issues are these:

1.When I trying to move the sprite on a slope or a lean barrier. The sprite will move off the slope which is not what I want.

2.ALternatively, I could use setPosition or CCAction which provides by cocos2d-x to move the sprite and update the body position use SetTransform. But the body will lost it's physical limitation, it will passthrough other body.

Thanks for your time, if you guys got any solution?


texts: box2D vs manual collision handling in libGDX

texts: I am developing a fairly simple game with Zelda-style physics where the only moving objects will be characters and other entities, however I am using a randomly generated (all in code, no .tmx) tile map which means I cannot immediately implement box2D as I would need to convert the tiled map into a box2D world, like in this question. My question is should I do collision checks manually, do the work to convert from a tile map to box2d, or just throw out the tile map (I'm not too far in that this is infeasible) and switch to a box2d world? And can I even use box2D for a top-down game?


texts: What the polycount limit for a mobile game character (heavily animated) is like if no shaders/lighting used in an otherwise simple scene?

texts:
I am making a few mobile game characters that will be heavily animated using about 15-20 bones. I am at the modeling phase of my game and just wanted an idea really. Good thing is that each level will only feature one such heavily-animated character and the enemy characters will be extremely low-poly and unanimated and few, and the scene itself will be simplistic. No shaders or lighting (unlit shader). So its just this one main hero character that I want to have as much detail as possible whilst being responsive.

Unity 3d used to make game and maya used to model,rig,animate.


texts:
I'm making some test with OpenGL and I've got a problem with my application design. Currently, I've got something like that in pseudo code:

// Ask to draw a given scene.
renderer->drawScene( myScene, myCamera );

// Here is what I do in the renderer
for( auto& mesh : scene->getElements() )
{
    this->draw(mesh);
}

// And here is what my draw method do.
// First geometry stuff.
context->setVertexFormat( mesh->geometry->vertexFormat );
context->setVertexBuffer( mesh->geometry->vertexBuffer ); // Use VAO is available.
context->setIndexBuffer( mesh->geometry->indexBuffer );

// Second, material stuff.
context->setProgram( mesh->material->program );
mesh->material->program->setParameter( "model", mesh->transform->position );
mesh->material->program->setParameter( "uCamera", camera.matrix );
context->setBlendMode(mesh->material->blendMode);

// Finally draw.
context->draw( mesh->material->drawingMode, mesh->geometry->indiceCount );

The problem is present with shader attributs, by exemple from main loop:

int main()
{
    while()
    {
        // I want change texture offset for the mesh N°7, that will change it for every mesh.
        myMesh7->material->program->setParameter("offset", 15.f);

        renderer->DrawScene(myScene, myCamera);
    }
}

How can I have a flexible design? A Shader/Program is shared with others meshes, so in the case where I would change "color" or "offset" attribute in my shader for only one mesh it's not possible. How can I handle that?

(I don't think it will be good to copy somewhere shader attributs per mesh)

Thanks for your help


texts:
When looking at the corners of skybox this happens:

http://i.imgur.com/H8XvS8I.jpg

How to get rid of this?

6 skybox textures are 2048x2048px each.

Tried changing Near and Far clipping of the main camera inside the character controller but it was ineffective.

If I look away from the corners the dark triangles dissapear. Only when I look directly at the corners they appear.


texts:
I've written a game in MonoGame, which works great on my desktop computer. It's running Windows 8, has a good graphics card and can be assumed to be up to date with everything.

However, when I run on my laptop, it crashes within the starting function game.Run(). I created a new template project, and it still crashes. I've check the obvious places, it's running x86 config, I've installed the openAL, and the dlls are in the right places.

The error is "NullReferenceException" occurred in MonoGame.Framework.dll

I can't post images, but I've changed nothing about the new project. It runs the init and the loadContent functions, then crashes.

The thing that might be important, the laptop has openGL 2.1, Windows 7. I have OpenTK, OpenAL installed. If anyone has even suggestions on things that might be the cause, or want more info, just say.

EDIT: The stack is as follows:

at Microsoft.Xna.Framework.Audio.OpenALSoundController.Update()
at Microsoft.Xna.Framework.OpenTKGamePlatform.BeforeUpdate(GameTime gameTime)
at Microsoft.Xna.Framework.Game.DoUpdate(GameTime gameTime)
at Microsoft.Xna.Framework.Game.Tick()
at Microsoft.Xna.Framework.OpenTKGameWindow.OnUpdateFrame(Object sender, FrameEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at OpenTK.GameWindow.OnUpdateFrame(FrameEventArgs e)
at OpenTK.GameWindow.OnUpdateFrameInternal(FrameEventArgs e)
at OpenTK.GameWindow.RaiseUpdateFrame(Stopwatch update_watch, Double& next_update, FrameEventArgs update_args)
at OpenTK.GameWindow.DispatchUpdateAndRenderFrame(Object sender, EventArgs e)
at OpenTK.GameWindow.Run(Double updates_per_second, Double frames_per_second)
at OpenTK.GameWindow.Run(Double updateRate)
at Microsoft.Xna.Framework.OpenTKGamePlatform.RunLoop()
at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
at Microsoft.Xna.Framework.Game.Run()
at Mojo.Program.Main(String[] args)

Posted as an error report to MonoGame, I'll answer this depending on their response.


texts: How do I sort with both depth and y-axis in OpenGL?

texts:
Continuing my misadventures in pyOpenGL, I've refactored the whole thing to use 4 buffers:

tile vertices - all drawn at the start, probably never modified
tile texture co-ords - not modified often (but enables support for animated tiles later)
sprite vertices - modified often as sprites move around the map
sprite texture co-ords - modified often as sprites animate

My draw loop binds each buffer, and calls drawArrays() twice. I have enabled depth testing, and clear the depth buffer on each draw:

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH)
...
glDepthFunc(GL_LESS)
glEnable(GL_DEPTH_TEST)
...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

For the moment, I've hard-coded the z coordinate for each of the things I'm drawing, just to be sure they're definitely in the right order - grass tiles are at 0.9, the tree (4 tiles) is set to -1.0 and the sprites are at 0.0. This is what I get:

In a previous attempt to build this engine without openGL, I was using Tkinter canvas images, which ended up very slow. To get the draw order right, I had to sort all the objects by their y-coordinate plus their z-coordinate, because it is all on a 2D plane. I want something similar, here. I don't understand why the grass tiles cause this problem, when they should be drawn right at the back. GL_DEPTH_TEST is definitely enabled - if I disable it by commenting out the glEnable() call, the sprites are drawn on top of everything (including on top of the trees). I want an illusion of depth by being able to walk behind high-sticking-up objects.

I've continued hacking away at this, and I've gotten a little further by modifying my shader:

fragment_shader = shaders.compileShader("""
    uniform sampler2D u_image;

    varying vec2 v_texCoords;

    void main()
    {
        vec4 tex = texture2D(u_image, v_texCoords);
        if(tex.a < 1.0)
          discard;
        gl_FragColor = tex; //texture2D(u_image, v_texCoords);
    }
""", GL_FRAGMENT_SHADER)

By checking for transparent pixels and throwing them away, I get a lot closer to my goal, however it is still not quite right, and I do not know how to fix it.

The wizard is at z:-0.5, and the tree trunk is at z:-0.2; it is doing what I'm telling it to do, just not what I want it to do. If I put them on the same z-level, the trunk is drawn over the wizard when he stands in front of the tree, and correctly when he stands behind it:

I don't just want depth sorting, I also want to sort on the y-axis. How can I do this in OpenGL?


texts:
In LibGDX how can I construct a 3D terrain model that has

Position
Normal
Color

The model does not require a texture, it is colored on a per vertex basis.
I've looked into LibGDX's ModelBuilder and MeshPartBuilder, but I can't seem to get it to work. I suspect this is a problem with indexing since I'm inexperienced on the subject.

So the question boils down to; In LibGDX, given positions (x, y, z), normals (nx, ny, nz), color (r, g, b, a) how can I construct a mesh / model with these vertex attributes and properly index them?

What I've tried so far:

final int attributes = Usage.Position | Usage.Normal | Usage.ColorPacked;
partBuilder = modelBuilder.part("Terrain", GL20.GL_TRIANGLES, attributes, material);

/*Generate vertices*/
for (int i = 0; i < VERTEX_COUNT; i++) {
    for (int j = 0; j < VERTEX_COUNT; j++) {
        final float x = j / ((float) VERTEX_COUNT - 1) * SIZE;
        final float z = i / ((float) VERTEX_COUNT - 1) * SIZE;
        final float y = MathUtils.random() * 10; // Testing different heights
        /*Position at (x,y,z), normal generated automatically*/
        partBuilder.vertex(new Vector3(x, y, z), null, Color.WHITE, null);
    }
}

/*Generate indices*/
for (short gz = 0; gz < VERTEX_COUNT - 1; gz++) {
    for (short gx = 0; gx < VERTEX_COUNT - 1; gx++) {
        final short topLeft = (short) ((gz * VERTEX_COUNT) + gx);
        final short topRight = (short) (topLeft + 1);
        final short bottomLeft = (short) (((gz + 1) * VERTEX_COUNT) + gx);
        final short bottomRight = (short) (bottomLeft + 1);
        partBuilder.index(topLeft, bottomLeft, topRight, topRight, bottomLeft, bottomRight);
    }
}

This doesn't work as I expected and generates the following result:


texts:
I've been getting reports from my users that sometimes the game isn't saving. I've recently been provided with the game save files from one of these reports and found all the XML files were completely empty, not even the headers.
There are two instances in which these files are edited, Steam Cloud Save, and my serialization system. Below are code snippets from both systems.
Can anyone identify an issue that may cause these files to be completely wiped?
public static void Save(object data, string fileName)
{
    var serializer = new XmlSerializer(data.GetType());
    Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(Application.persistentDataPath, fileName)));
    using (var stream = new FileStream(Path.Combine(Application.persistentDataPath, fileName), FileMode.Create))
    {
        serializer.Serialize(stream, data);
    }
}

string path = Path.Combine(UnityEngine.Application.persistentDataPath, name);
if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path));

byte[] file = SteamRemoteStorage.FileRead(name);

if (file != null)
{
    File.WriteAllBytes(path, file);
}