texts:
I've been looking at a couple of games and noticed that the transitions between tiles are handled somewhat different.

I was wondering which methods are to be used in different situations and why. I'm currently using internal edges in a top-down game, and it's working out so far. But I don't want to run into problems later on, and have to redo the whole tileset.

I noticed that platforming games mostly use the internal edges, and top-down games mostly use external and hybrid transitions. I can see how these tiles are used to create "depth" in top-down games, where the player apears to be standing in front of a wall for example. But it seems unlikely that such a small feature decides the entire method for tile transitions. You could always alter the bounding box to create the same effect.


texts:
I want to animate my character in game. My graphic animator prepare for me three options.

Frame-by-frame by this is over 9MB for one animation. With TextureSpriter 4-5MB.
Spriter but I can't find how to handle scml in GLES 2.
FLA/SWF and this is my best promissing option because size of swf with animation is 1,8 MB. But so far I google that flash is no longer supported in android and it's big issue to use it with AndEngine.

What's more I found this question maybe something is changed since '13.

So I guess I got only option 1. Am I wrong? What do you use to animate?


texts: How do i initialize and use a Texture Array? LibGDX

texts:
First of all, I am new to Java and LibGDX..

What I am trying to do is Load my texture images into an array so that I can reference them in my drawing code by number, rather than by name.
I am drawing a tile map.

Instead of this:

tile1 = new Texture(Gdx.files.internal("grass.png"));
tile2 = new Texture(Gdx.files.internal("dirttile.png"));
tile3 = new Texture(Gdx.files.internal("watertile.png"));

I would like it to be more like:

tile[1] = new Texture(Gdx.files.internal("grass.png"));
tile[2] = new Texture(Gdx.files.internal("dirttile.png"));
tile[3] = new Texture(Gdx.files.internal("watertile.png"));

..so that later I can draw them by which tile I need..such as

tileType = worldMap[i][j]; //will be an int number
batch.draw(tile[tileType], tileX, tileY);

I can't figure out how to initialize array and load textures into it though in order to do this, without getting errors.

Basically I need to draw my map based on numbers I have in a tile map like this:

 int worldMap[][] = {
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,3,3,3,1,1,1,1 } ,
            { 1,1,1,3,3,3,1,1,1,1 } ,
            { 1,1,1,3,3,3,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
            { 1,1,1,1,1,1,1,1,1,1 } ,
    };

I need to draw the map tile based on the numbers in that map... 1 = grass 2 = dirt 3 = water etc....
Still no luck getting the array working.


texts: Mirroring a game object to create symmetry

texts:
I have a GameObject with a primitive shape that I call "body". I want to create and add a child to it with another primitive shape. I call it 'mutation'. But i want to duplicate the 'mutation' and mirror the duplicate. So they become symmetrical to the 'body'. This way it could resemble wings or legs or eyes.

I've tried to create two children to the mutation called "LeftSide" and "RightSide". I duplicated the new primitive and put one copy in each. I set the Left Side's scale to -1 for the X, Y and Z hoping that it would mirror and create a symmetry with the right side. But its not working out.

So I'm hoping for some tips on ideas on how to achieve this?


texts: Scaling along an arbitrary axis (Dealing with non-uniform scale)

texts:
I'm trying to build my own little engine to get more familiar with the concepts of 3D programming.

I have a transform class that on each frame it creates a Scaling Matrix (S), a Rotation Matrix from a Quaternion (R) and concatenates them together (S*R). Once i have SR, I insert the translation values into the bottom of the three columns. So i end up with a transformation matrix that looks like:

[SR SR SR 0]
[SR SR SR 0]
[SR SR SR 0]
[tx ty tz 1]

This works perfectly in all cases except when rotating an object that has a non-uniform scale.

For example a unit cube with ScaleX = 4, ScaleY = 2, ScaleZ = 1 will give me a rectangular box that is 4 times as wide as the depth and twice as high as the depth.

If i then translate this around, the box stays the same and looks normal.

The problem happens whenever I try to rotate this scaled box. The shape itself becomes distorted and it appears as though the Scale factors are affecting the object on the World X,Y,Z axis rather than the local X,Y,Z axis of the object.

I've done some pretty extensive research through a variety of textbooks (Eberly, Moller/Hoffman, Phar etc) and there isn't a ton there to go off of. Online, most of the answers say to avoid non-uniform scaling which I understand the desire to avoid it, but I'd still like to figure out how to support it.

The only thing I can think off is that when constructing a Scale Matrix:

[sx 0  0  0]
[0  sy 0  0]
[0  0  sz 0]
[0  0  0  1]

This is scaling along the World Axis instead of the object's local Direction, Up and Right vectors or it's local Z, Y, X axis.

Does anyone have any tips or ideas on how to handle construction a transformation matrix that allows for non-uniform scaling and rotation?

Thanks!


texts: How to create sprites, programatically without using prefabs?

texts:
I have different types of images for different sprites. and i am not certain that how much different sprites(images) i will have to show. So, i gotta create the sprites and apply textures programatically at runtime.

Now, I defiantly can't use prefabs because it will restrict me with the number of different sprites i can use. and also, changing texture on one sprite prefab instance in game, will change all the sprites prefab, that's not acceptable in my case.

Is there a way i can create sprites without having to create static prefab ?

where ever i looked for the solution every time i got the same answer "create a prefab", which is what can not be done in my case.


texts: How to disable player-player/player-monster collisions and keep the OnTrigger/OnCollision hooks?

texts:
I'm developing a network game. Players and enemies have attached Rigidbodies, move with physics forces, stops on kinematic colliders (walls) - everything works pretty well. Now it's the time for player-player and player-monster coliisions.

In my case, the player should be unpushable, even by other players and monsters.

The problem with that is if all 'moving/non-kinematic' objects have rigidbodies, they can move/push each other as they move - which is wrong in my case. I came up with an idea that I'll disable collisions between these objects through layers and did that.

I also wrote a script which pushes the object back (in the opposite direction) when triggered which I want to apply.

The problem is here, that I need to preserve the original collider (non-trigger) so the player can be stopped by walls AND I need to detect other players in OnTriggerEnter() so I can push them back so they don't overlap.

This is quite easy - I need two colliders attached to the player:

a non-trigger one - responsible for the ground, walls, physics driven
a trigger one - for interaction with players and enemies (to push them)

I also need to disable built-in collisions between players through the physics layers and listen for "Player" and "Monster" tags in OnTrigger().

Does this all make sense? How would you improve this? Is there a quicker way to achieve this? Two colliders seem not that bad - but it's still two instead of one.

In order to visualize what I want to achieve:

Games I know have collisions like this are Diablo 3 and League of Legends probably.


texts:
I use an Arduino and a 9dof sensor ( gyroscope, accelerometer and magnetometer ) and i'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.

I managed to correctly compute pitch and roll ( the z and x axis in unity ) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my Yaw too in a weird way.

Code in the arduino to get the heading

void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

Pitch and roll

    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

Don't hesitate to ask for details.


texts: Can I create new UI elements and use them from Unity?

texts:
I created the following class, that should be used to display numeric text in a UI canvas (score, lives, etc.):

public class NumericField: UnityEngine.UI.Text {
    [SerializeField] int value = 0;

    override protected void Start() {
        base.Start();
        text = value.ToString();
    }

    public int Get() {
        return value;
    }

    public void Set(int newValue) {
        value = newValue;
        text = value.ToString();
    }

    public void Add(int toAdd) {
        Set(value + toAdd);
    }
}

Now, I would like to add a NumericField into my Canvas, instead of adding a Text. But, when I right-click the Canvas object, I do not see my NumericField. How can I add it to the menus, so that I can add it to the canvas?


texts: How to use the Object parameter in UInputComponent.BindAction?

texts:
What is the purpose of the Object parameter here?

UInputComponent.BindAction(..., UserClass* Object, ...)

What information should I pass here?


texts: How do i get a kniematic body to collide with my tilemap?

texts:
My kinematic body does not sense collision with my tilemap.  Ive defined collision for the tilemap via the drag and drop collision boxes in the tileset.  I dont know what could be the issue.
KinematicBody2D
extends KinematicBody2D

export var max_speed = 48
export var min_speed = 16
export var acceleration = 4
var speed = min_speed

# Called when the node enters the scene tree for the first time.
func _ready():
    pass

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
    var velocity = Vector2()
    if Input.is_action_pressed("ui_up"):
        velocity.y -= 1
    if Input.is_action_pressed("ui_left"):
        velocity.x -= 1
    if Input.is_action_pressed("ui_down"):
        velocity.y += 1
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1
    if Input.is_key_pressed(KEY_Q):
        speed += acceleration
        speed = clamp(speed,min_speed,max_speed)
    else:
        speed -= acceleration
        speed = clamp(speed,min_speed,max_speed)
    if velocity.length() > 0:
        velocity = velocity.normalized() * speed
    var collision = self.move_and_collide(velocity * delta)
    if collision:
        print_debug("collision")

https://github.com/MonkeyToiletLadder/godotTilemap
I'm hoping someone can download my project settings and see what the issue is. Id be happy if i got a working example from someone.  Thank you.


texts: How to find sequences of consecutive cards of the same suit in a hand, including wild cards? (Indian Rummy)

texts:
I have a hand of 13 cards (chosen from 2 standard decks of 52 cards + 4 jokers, so it's possible for the same card to appear multiple times).

I want to search this deck to find sequences according to the rules of Indian Rummy:

A sequence must contain at least 3 cards, or up to 10 cards

(We need at least two sequences to win / minimize loss penalties, so at least 3 cards in the hand of 13 need to be left over to form another sequence)
Cards in a sequence have consecutive rank:

2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A (wild cards count as any rank)
A sequence must be all of the same suit:

♦, ♣, ♠, ♥ (wild cards can count as any suit)
A sequence is called "pure" if it contains no wild cards standing in for other cards.

eg. if Jacks are wild, the sequence 10♥, J♥, Q♥ is a pure sequence, while the (also valid) sequence 3♣, 4♣, 5♣, J♥, 7♣ is not a pure sequence.

Here's what I've come up with so far, but it does not correctly find all sequences matching the rules above.

private List<Card> FindSequences()
{
    List<Card> sequence = new List<Card>();

    int Count = 0;

    //sort in order
    cards = cards.OrderBy (i => i.FaceValue).ToList ();
    sequence.Add(cards[Count]);

    //------------------------------------------------------------------------------------------------------//

    for(int i = 1; i < 9; i++)
    {
        if((cards[i - 1].cardRank == cards[i].cardRank - 1) && (cards[i].cardRank == cards[i + 1].cardRank - 1) && (cards[i + 1].cardRank == cards[i + 2].cardRank - 1) )//&& (cards[i + 2].cardRank == cards[i + 3].cardRank - 1))
        {
            sequence.Add (cards [i - 1]);
            sequence.Add (cards [i]);
            sequence.Add (cards [i + 1]);
        }
        else
        {
            Count++;
            //check If Sequence Less Then 3 Clear Data
            if(sequence.Count < 3)
                sequence.Clear ();
        }
    }

    wildCard.Clear ();
    return sequence;
}


texts: Designing the Update system (read very basic game engine) for an XNA game

texts:
I am trying to determine the best way to implement the "update" system or engine for a simple XNA game.

Description of situation

I have a few classes, lets call them:

Player [will be an array/list/collection of 1-4 local players]
Enemy [will consist of all enemy characters in the given "zone"]
Future [not implemented, may not be implemented for this game, but may be needed in future]
Future

I'm trying to decide what the best way to manage this will be, I'm going back and forth between a couple options.

First Approach

In the Update() method of my game, write code like this:

void Update(GameTime gameTime)
{
    var ctlInput = GetControllerInput();
    for(int i = 0; i < 4; i++)
    {
        if(Player[i] != null) { Player[i].Update(gameTime, ctlInput); }
    }

    for(int i = 0; i < Enemy.Count; i++)
    {
        Enemy[i].Update(gameTime, Player);
    }
}

In this version, I would add "FrameStatus" fields to the Player class, which would look like bool IsShooting and Vector2 TargetedLocation etc. This also means that each class would be responsible for knowing how to update itself in the game world.

In my eyes, the advantages of this approach are:

No new classes.
Classes become self-documenting
Easy to extend and add additional properties

but the disadvantages are:

Order of code in Game.Update is very important
Tight coupling of Player and Enemy classes

Second Approach

Implement a type of UpdateManager class, which accepts the user input, and it alone updates the Player and Enemy classes. This would relegate the Player and Enemy classes to simply dumb-data classes, and they wouldn't necessarily have any game logic in them at all.

void Update(GameTime gameTime)
{
    var ctlInput = GetcontrollerInput();
    updateManager.Update(gameTime, ctlInput);
}

The advantages of this approach, in my eyes, are:

Keeps code away from Game.Update()
Doesn't require Player and Enemy classes to know about each other at all

Disadvantages as I see it:

Adds a new class to my game
The new class, will have a lot of code as time goes on and more types of objects enter the game world

Actual Question

Of the pro/cons I've come up with for my two approaches,

do you think I've missed any, what are they?
which makes you lean for or against an approach, why?

Which approach would you take, and also why would you go that route? Would you elect for a third option? What would that option look like?


texts: Looping an object to move between two positions

texts:
I've search a bit and tried to find a decent answer to this but have failed majorly.
Basically I'm trying to loop an AI object between two points. Heres some of the code I have so far:

class Object
{
    Vector3 startPos;
    Vector3 endPos;

    Vector3 curPos;
    Vector3 curVel;
};

struct Vector3
{
    float x;
    float y;
    float z;
}

Start()
{
    startPos = Vector3( 1, 0, 0 );
    endPos = Vector3( -1, 0, 0 );
    curPos = Vector3( 0, 0, 0 )

    Generate();
}

Generate()
{
    // Standard code to generate angular velocity
    // Calculate angle between two points
    // Calculate velocity based on angle
}

Update()
{
    // Add velocity
    curPos += curVel;

    // If the position has reached the end point
    if( curPos == endPos )
    {
        // Reverse movement positions
        Vector3 temp = endPos;
        startPos = endPos;
        endPos = temp;

        // Recalculate velocity
        Generate();
    }
}

I'm now stuck, as you can see from the comments, the velocity could take the position of the object to something like (-1.5, 0, 0) which would mean the if statement wouldn't work.
For the initial movement, it could be fixed using

if( curPos <= endPos )
{
    // Reverse
}

However, when I then reverse the positions, problems arise and it won't work.
Any ideas?


texts: in Unity3d, how to automatically create fixed joints in a wall of cubes?

texts:
I want to create a wall:
width  6 cubes
height 7 cubes

therefore I have 22 cubes on the margins and 20 cubes inside. For each of the margins cubes(except the corners) I have to set 3 fixed joints, and for the cubes inside the wall I have to set 4 fixed joints - all this to have good physics behavior.

Pretty much I have to create a fixed joint between a cube and all his neighbors => and that's a lot!
Is there a way to automatically create these fixed joints?

Is there another way to create a physics friendly wall? I want to simulate a wall of bricks hited by a projectile.


texts: LibNoise Perlin.GetValue not returning noise for zero decimal place numbers

texts:
I'm using the LibNoise port from C++ to C# and running into problems generating Perlin noise (Unity demo here). For some odd reason integers never generate any noise. In the code below _firstValue on all axis has no decimal places and with perlin.GetValue(_firstValue); it returns zero. Adding a decimal place to either x/y/z of _firstValue will return a value with perlin.GetValue.

If anyone's ever used this library, any ideas on why something so simple like this demo seems to be causing so much of a head ache? Looking through the Perlin class, everything seems OK.

Vector3 _firstValue = new Vector3(-31.0f, 83.0f, -7.0f);

Vector3 _displacement = 0.0001f * Vector3.one;

Vector3 _secondValue = new Vector3(14.50f, 20.25f, 75.75f);

// Use this for initialization
void Start ()
{
    Debug.Log("Tutorial conversion for http://libnoise.sourceforge.net/tutorials/tutorial2.html");
    var perlin = new Perlin();
    Debug.Log(string.Format("First value: {0}", perlin.GetValue(_firstValue)));
    Debug.Log(string.Format("First value, displaced: {0}", perlin.GetValue(_firstValue + _displacement)));
    Debug.Log(string.Format("Second value: {0}", perlin.GetValue(_secondValue)));
}


texts: Old "Play Montage" node vs new 'Montage Play" and "Play Anim Montage"

texts:
so.. Following documentation/guides/etc.. I keep coming across the classical node called "Play Montage" which shows one of those Mario Bros pipes as an icon.

However, my version of unreal engine does not have that BP node. it only has "Montage Play" and "Play Anim Montage". As far as I can tell the difference is that there are different input nodes in each of the three cases, and the "Montage Play" is aimed at an Anim instance while the Play Anim Montage is aimed at character.

Could anyone help me out here and illustrate the real difference between all 3? Thank you :)

This is the old one:

These are the new ones:


texts: How can I easily assign an array in the inspector?

texts:
If you make a public array class member in Unity, you can individually assign objects to the array in the inspector menu. It looks like this:

However, this is cumbersome if you you want to assign the same array to many objects. It's easy to do this programatically, but I'd rather not hard-define the array in code - it makes moving/renaming the objects harder.

If I want to pass the same array to multiple game objects, how can I do it more efficiently than dragging each individual element into the inspector?


texts:
I got an error, when I launch fireball too swiftly, I guess, my fireball does not really remove well.  So that's why I got crush..
Can you guys check my update method, and please give me some idea?

And one more thing I want know is what !world.isLocked() means...

public class FireBall extends Sprite {

    PlayScreen screen;
    World world;
    Array<TextureRegion> frames;
    Animation fireAnimation;
    float stateTime;
    float firetiem;
  public static  boolean destroyed;
    boolean setToDestroy;
    boolean fireRight;

   public static Body b2body;
    public FireBall(PlayScreen screen, float x, float y, boolean fireRight){
        this.world = screen.getWorld();
        this.fireRight = fireRight;
        this.screen = screen;
        destroyed = false;
        frames = new Array<TextureRegion>();
        for(int i = 0; i < 4; i++){
            frames.add(new TextureRegion(screen.getAtlas().findRegion("fireball"), i * 8, 0, 8, 8));
        }
        fireAnimation = new Animation(0.2f, frames);
        setRegion((TextureRegion)fireAnimation.getKeyFrame(0));
        setBounds(x, y, 6 / MarioBros.PPM, 6 / MarioBros.PPM);
        defineFireBall();
    }

    public void defineFireBall(){
        BodyDef bdef = new BodyDef();
        bdef.position.set(fireRight ? getX() + 12 /MarioBros.PPM   :  getX() - 12 /MarioBros.PPM, getY());
        bdef.type = BodyDef.BodyType.DynamicBody;
        if(!world.isLocked())
        b2body = world.createBody(bdef);//?

        FixtureDef fdef = new FixtureDef();
        CircleShape shape = new CircleShape();
        shape.setRadius(3 / MarioBros.PPM);
        fdef.filter.categoryBits = MarioBros.FIREBALL_BIT;
        fdef.filter.maskBits =  MarioBros.GROUND_BIT | MarioBros.ENEMY_HEAD_BIT|
                MarioBros.COIN_BIT |
                MarioBros.BRICK_BIT |
                MarioBros.ENEMY_BIT|
                MarioBros.OBJECT_BIT;

        fdef.shape = shape;
        fdef.restitution = 1;
        fdef.friction = 0;
        b2body.setLinearVelocity(new Vector2(fireRight ? 2 : -2, 2.5f));
        b2body.createFixture(fdef).setUserData(this);

    }

    public void update(float dt){
        stateTime += dt;

        setRegion((TextureRegion) fireAnimation.getKeyFrame(stateTime, true));
        setPosition(b2body.getPosition().x - getWidth() / 2, b2body.getPosition().y - getHeight() / 2);

        if((stateTime > 0.5f &&  !destroyed)) {
            System.out.println("remove");
            world.destroyBody(b2body);
            destroyed = true;
            stateTime=0;
            }

        if(b2body.getLinearVelocity().y > 2f)
            b2body.setLinearVelocity(b2body.getLinearVelocity().x, 2f);

        }

    public boolean isDestroyed(){
        return destroyed;
    }}


texts: Converting data file of Sprite Atlas from JSON to Cocos 2D

texts:
I have an existing Sprite Atlas with its data file in JSON format. How do I convert it for use with Cocos 2D and other frameworks ?

I tried poking around in Texture Packer which supports publishing to multiple formats. But I can't figure out how to convert from one format to another

EDIT : Is there any other software that is able to convert between different formats ?


texts: How should I implement parallax scrolling with pan and zoom in HTML5?

texts:
I'm writing a planetary motion simulator with the HTML5 canvas element and I want to put one or more layers of stars in the background. The user can click and drag the screen to navigate around the map as well as zoom in and out. The map is infinite; they could scroll forever in any direction. I'd like to have the background layer move more slowly than the foreground so as to give the illusion of depth.

How should I go about implementing this? Can I load an image file and tile it? Should I create an SVG image? Should I just use the CanvasRenderingContext2D.fill() to create the background? I'm trying to keep the game running as close to 60fps as possible.


texts:
I am trying to apply this texture as a cubemap. This is my result:

Clearly I am doing something with my texture coordinates, but I cannot for the life of me figure out what. I don't even see a pattern to the texture fragments. They just seem like a jumble of different faces. Can anyone shed some light on this?

Vertex shader:

#version 400
in  vec4 vPosition;
in  vec3 inTexCoord;

smooth out vec3 texCoord;

uniform mat4 projMatrix;

void main()
{
   texCoord = inTexCoord;
   gl_Position = projMatrix * vPosition;
}

My fragment shader:

#version 400
smooth in vec3 texCoord;

out vec4 fColor;

uniform samplerCube textures

void main()
{
           fColor = texture(textures,texCoord);
}

Vertices of cube:

point4 worldVerts[8] = {
    vec4(  15,  15,  15, 1 ),
    vec4( -15,  15,  15, 1 ),
    vec4( -15,  15, -15, 1 ),
    vec4(  15,  15, -15, 1 ),
    vec4( -15, -15,  15, 1 ),
    vec4(  15, -15,  15, 1 ),
    vec4(  15, -15, -15, 1 ),
    vec4( -15, -15, -15, 1 )
};

Cube rendering:

void
worldCube(point4* verts, int& Index, point4* points, vec3* texVerts)
{

    quadInv( verts[0], verts[1], verts[2], verts[3], 1, Index, points, texVerts);
    quadInv( verts[6], verts[3], verts[2], verts[7], 2, Index, points, texVerts);
    quadInv( verts[4], verts[5], verts[6], verts[7], 3, Index, points, texVerts);
    quadInv( verts[4], verts[1], verts[0], verts[5], 4, Index, points, texVerts);
    quadInv( verts[5], verts[0], verts[3], verts[6], 5, Index, points, texVerts);
    quadInv( verts[4], verts[7], verts[2], verts[1], 6, Index, points, texVerts);
}

Backface function (since this is the inside of the cube):

void quadInv( const point4& a, const point4& b, const point4& c, const point4& d ,
      int& Index, point4* points, vec3* texVerts)

{
    quad( a, d, c, b, Index, points, texVerts, a.to_3(), d.to_3(), c.to_3(), b.to_3());
}

And the quad drawing function:

void quad( const point4& a, const point4& b, const point4& c, const point4& d,
      int& Index, point4* points, vec3* texVerts, const vec3& tex_a, const vec3& tex_b, const vec3& tex_c, const vec3& tex_d)

{
    texVerts[Index] = tex_a.normalized(); points[Index] = a; Index++;
    texVerts[Index] = tex_b.normalized(); points[Index] = b; Index++;
    texVerts[Index] = tex_c.normalized(); points[Index] = c; Index++;
    texVerts[Index] = tex_a.normalized(); points[Index] = a; Index++;
    texVerts[Index] = tex_c.normalized(); points[Index] = c; Index++;
    texVerts[Index] = tex_d.normalized(); points[Index] = d; Index++;
}

Edit: I forgot to mention, in the image, the camera is pointed directly at the back face of the cube. You can kind of see the diagonals leading out of the corners, if you squint.

I tried writing the texture coordinates as colors as Nathan Reed suggested, and still got random values from the fragment shader, so I tried replacing all texture coordinates with (0,1,0) (so as colors, all faces should be green). Instead, I got this:

Old result with b and d vertices swapped in texture:


texts: How can I put a Unity3D game on an Xbox 360 disc?

texts:
I've made a simple shooter in Unity that I'd like to play on an Xbox 360. Mass production not required, just a one-off game, completely non-profit. Perhaps burning to a DVD?

Is it a relatively simple procedure to burn the game to disc? I have a nasty feeling the Xbox 360 needs to be chipped. Is this the case?


texts: Is there a 3D format that supports instanced components?

texts: I am looking for a 3D file format that supports instanced components/objects. That is, there is one geometry declaration and then it is instanced in numerous places. Open formats are very much preferred.


texts: UDP Netcode Architecture for Fighting Game

texts:
I am programming a fighting game that uses a UDP client/server architecture for multiplayer. The server can handle multiple clients, two of which (or one being the server) are playing and the rest are watching and chatting. I would prefer to use UDP for everything, including: player input from client, player state from server, and chat going both ways.

My concern is keeping the order of the player inputs in sync from the client to the server. Since moves involve a specific sequence of inputs (e.g., Left,Left-down,Down,Light Punch), if the server processes them out of order then the game is ruined. What is a good approach for dealing with packet loss and packets arriving out of order in this case?

I have considered having a linked list of outgoing packets in the client and server. With each step the list is traversed and unsent packets are sent, and if an ack packet(one I program the receiver to send back) was received for a particular packet (which I can identify simply with an integral value) then the outgoing packet is removed from the list. However, this does not guarantee order of delivery. Perhaps the server could keep a queue of inputs and evaluate another integral value in the packet for each input, organizing them into the correct order.

I'm not entirely sure, if someone could point me in the right direction I would be very grateful. I have working client and server chat code but before I starting seriously designing the network architecture I wanted to see what others have to say.


texts: Properly rendering transparent areas of textures

texts:
I'm rendering a tree that contains branch meshes with partially transparent textures.

If I render it with AlphaTestEffect and set the ReferenceAlpha to something low, I'll get this.

I want to render the tree with BasicEffect, however, this is the result I get. BlendState is set to NonPremultiplied.

I am not even sure what I am looking at. It looks like the transparent area of the closest branch is covering up the one behind it (but not the trunk of the tree). If I set the DepthState to DepthRead, then all the branches are drawn out of order.

What exactly is the problem here?


texts: What are mental ray shaders and can I use them in my own game?

texts:
I'm using the FBX SDK to import and display FBX models in my OpenGL app. It works fine so far with a simple phong shader and displays basic models.

However I have some FBX models that have custom (Mental Ray) Arch & Design materials. Can I render these models with such materials in my app?

My (completely noob) understanding of how this works is that the Arch & Design thing is a shader. A graphic designer edited some data fields, and the way the model is rendered is that such data is passed to the Arch & Design shader during rendering, and the shader takes care of it (ie does all the lighting calculations etc).

Is it possible for me to use that flashy Arch & Design shader in my app, so I manually parse the FBX model and send the data fields to the shader? How do I get hold of it?

Any clarification will be appreciated, you can probably tell that I'm somewhat confused.


texts: How to get the "(human) Face" position from Webcam Texture

texts:
I am searching a way to recalculate the current Position of the Face in "Virtual World Position" From a Webcam Texture.
I was thinking about a way to solve this via taking the Average Pupillary distance (which is ~60mm).
And...
With this number I somehow need to get a actual position ... somehow... of the... Face...  (The Center)

I dont know how exactly though.
Any Ideas?


texts: Implementing top view physics using box2D

texts: How can top view physics games be done in box2D? One idea I have is to set the linear velocity of an object manually or to alter the linear and angular damping as my object moves over different surfaces. For example if my object is over a wet surface it'll have less linear damping and if it is over rough surface it'll have more damping. And to see if my object has fallen over an edge I'll try to use an AABB and check if its still inside or manually see if object.x > boundary.x etc. Is there any better way?


texts:
I am writing a simple 3D pacman using c++ and OpenGL. I'm new in OpenGL development, I wanted to make a small project before learning next concepts.

For now I can't have more than 55fps when rendering every objects.

These are my objects is the game :

After commenting my code to see which objects was causing problems, I know that the grid ( that is oly a plane, so 6 vertices ) and the walls ( 17k vertices, 1 draw call ) are causing the problems. ( By commenting all other elements, like foods, player and ghosts I only win 5 fps )

Which leads me to this question : What really matters with frame rate? The number of draw calls? The number or indices it has to render? the number of pixel that will be visible in the screen? Everything?

It seems that vertices outside the screen are ignored, but if that's true, how can I improve my fps count?

Or maybe I am just worrying for nothing and that's a normal thing with the first projects and should just continue?

Thanks for the help.


texts: How to make my multiplayer Air Hockey better?

texts:
I've made simple multiplayer web game but don't like how it works. Here's a video example (captured at 85 avg ping) showing what I have.
What I used:

Super naive client prediction - called so because there is no reconciliation - most of the time players' strikers can't be moved by anything except players themselves

Interpolation (it's turned off on the attached video because at the current state of the game in combination with prediction it made things look worse. Without prediction input lag is unacceptably big)

I've read some valve wiki articles, Gambetta's articles and some other not so popular sources, which helped to understand general ideas, but I still lack understanding on how to combine various techniques of minimizing delays for players and some implementation details. So here are the questions:

What is the best way to sync time on client and server and when to start clocks? I should measure average ping and then what? Server sends notifications to clients 'start clocking in X ms' based on ping? Should they even start clocking at the same time?

How to improve user experience for my game? I guess I should probably use extrapolation for puck

Is interpolation even needed with 60 tickrate for anything with 60 or lower hz screens? I'm not aiming at e-sports level experience and would rather make it feel nicer for 60 hz phone screens


texts: Which GameObject should I put the animator on?

texts:
I have a GameObject.  One of its children is an empty GameObject, whose children are the body parts which need to be animated.

Character (root)
--->Body
--->--->Body Parts

Should I put the animator on the root GameObject ("Character")?  Or on the empty child ("Body")?  Does it matter? What benefits would one way offer over the other?  Or is there another approach I should be taking?

This is for 2D sprites/animations.  I am trying to figure this out before making all of the animations to avoid redoing them.


texts: Incorrect placement of diacritics in Arabic fonts

texts:
I put AdobeNaskh font on my texts and use Arabic text support for unity and use show Tashkeel function then the text appears so

what is the solution of this problem?


texts: How can I get six Xbox controllers to provide input to an HTML5 game?

texts:
I'm creating a six player HTML 5 game designed to be played locally (Red Ice).

I've previous set up handling 7 Wiimotes using something along the lines of Joy2Key to map each input for each player to a separate keyboard key, but Wiimotes are pretty hard on the hands for these types of games and not very ergonomic so I thought I'd try and get Xbox controller support.

I don't believe that any simple key mapping solution will work due to the nature of the directional stick.

My inclination is that this will require a browser plugin and if so I'd prefer to write the plugin for Google Chrome.

How do I create a Chrome browser plugin to handle multiple Xbox controllers or is there some other way?

Please do not answer this question saying it can't be done, because it absolutely can.

EDIT: I don't believe any keymapping/mouse simulating solution will work unless it can reliably distinguish six axis of inputs, one per player.


texts: Authoritative server controlling objects in multiple scenes in Unity3D

texts:
I am working on a multiplayer project that involves loading into different scenes and playing some kind of mini-game with any other players that happen to be in the scene at that time.  These mini-games will contain AI that needs to be controlled by a dedicated server.  Additionally, there is simulation that needs to happen in these scenes, even if no player is currently in one.
My first idea to take a crack at this was to have my server on startup, load all of the scenes in the game using LoadSceneMode.Additive This way, on the server side, each scene would be in one place and available to be simulated.
I made a little sample project with three scenes, a base world, and two other worlds. When the server is started from the Base World scene, it loads World1 and World2 into its scene.  From my server, I could spawn a cube in World1 by pressing the 1 key, and I could spawn a cube in World2 by pressing the 2 key.
I used the following code to spawn the cube:
    GameObject cube = (GameObject)Instantiate(myPrefab, new Vector3(0, 10, 0), Quaternion.identity);
    NetworkServer.Spawn(cube);

The problem is, if a cube is spawned in World1, clients in World2 still spawn the cube.  In hindsight this makes sense because the documentation for NetworkServer.Spawn states

Spawn the given game object on all clients which are ready.

My next idea was that I could designate one player in the minigame as a psuedo "host" and his machine would be responsible for running the AI.  However, with this method, I really cant simulate things going on when nobody is in the scene.
Is there a better way I should go about solving this problem?  How can I create a dedicated server which can simulate multiple scenes at once? Should each scene be handled by its own server? Am I better off just trying to run everything in one scene?


texts: Implementing Branching Conversation Dialogue in C# with XNA

texts:
How could I add logical branching conversation dialogue in C# with XNA? What I mean by this is a dialogue tree similar to this:

If the user is wearing red:
     DisplayText "You're wearing a red shirt!"
Else:
     DisplayText "You're not wearing a red shirt!"

The key is that I can't hard-code these logic questions into C# itself; it has to be readable from some sort of external file and still executable.

My question is very similar to this question: How can I implement dialog trees into my game?

But my focus is more on how I can actually begin to implement this feature into my game.


texts: Can GJK be used with the same "direction finding method" every time?

texts:
In my deliberations on GJK (after watching http://mollyrocket.com/849) I came up with the idea that it ins not neccessary to use different methods for getting the new direction in the doSimplex function.

E.g. if the point A is closest to the origin, the video author uses the negative position vector AO as the direction in which the next point is searched. If an edge (with A as an endpoint) is closest, he creates a normal vector to this edge, lying in the plane the edge and AO form. If a face is the feature closest to the origin, he uses even another method (which I can't recite from memory right now)

However, while thinking about the implementation of GJK in my current came, I noticed that the negative direction vector of the newest simplex point would always make a good direction vector.

Of course, the next vertex found by the support function could form a simplex that less likely encases the origin, but I assume it would still work.

Since I'm currently experiencing problems with my (yet unfinished) implementation, I wanted to ask whether this method of forming the direction vector is usable or not.


texts:
Is there a way to check the consistency of a DirectX model (.x) ?

Whilst compiling .x files with XNA GameStudio 3.1 compilation is aborted with the following error message:

Error  2   Could not read the X file. The file is corrupt or invalid. Error code: D3DXFERR_PARSEERROR. C:\WFP\Browser\Content\m.x  KiviBrowser

Some models compile correctly without any error/warning and some abort as described. The files of each model have several thousand lines.

I am creating the files in Googles SketchUp 8 where they all look fine and don't show any sign of corruption.

Suppose I have such a model my XNA compiler won't compile because their is an inconsistency somewhere in the file - how could I identify this in order to correct it ?


texts: How can I improve the performance of handling many objects to draw in XNA?

texts:
I have a 2D engine that uses XNA 4.0. I have an issue with handling many objects.
In my engine, I only draw visible sprites, and ignore sprites outside of the current viewport. It works, so far. I also use a RenderTarget to minimize the amount of sprite batch being called, to draw the base.

I also need to draw buildable objects, and the worst case is that there is a list with 10,000 - 20,000 objects. I need to iterate through them, to find the visible buildable objects, as well. This really affects my frame rate, especially when the viewport changes.

I could decrease the zoom level, to minimize the amount of base tiles, but the list of objects keeps the same. Using smaller texture sizes could help, but then I´m also losing detail.

How could I improve the performance?


texts: ATI driver bug and rendering to a texture 2d array in OpenGL

texts: I am trying to render to a texture2Darray in OpenGL, with a similar setup as descriped in this post. My question is, if anyone has gotten this to work on ATI hardware? Or is there still a bug in the driver, preventing multi layered rendering? The bug is also mentioned in the forum post.


texts:
I absolutely don't know what is the problem with this code and I have tried everything without any success. I need help.

void FixedUpdate()
{
if (Physics.Raycast(transform.localPosition+new Vector3(0f,0.1f,0f),-transform.up,0.2f) )
        {
            grounded = true;
        } else
            grounded = false;

if (Input.GetButtonDown ("Jump") && grounded)

            {
                rb.velocity+= Vector3.up*jumpSpeed;

            }
}

Some time it jumps and some time it doesn't jump with no visible pattern.


texts:
I'm currently creating a game framework/engine for educational games. My hope is that this can be used in elementary schools. It is of course extremely important that the games are both fun and educational.

Any ideas what should be in my initial requirement specification?

What makes a good educational game?

Which platforms should I target?


texts: Calculate Discrete Fourier Transform by using c#

texts:
There is a definition of Discrete Fourier Transform:

I want to calculate amplitude and phase of a transformed sequence.

I tried :

 public ArrayList phase = new ArrayList();
 public ArrayList amp = new ArrayList();
 public float phi = 0;

 void Start ()
 {
      DFT();
      foreach (var ampList in amp)
      {
        Debug.Log(ampList);
      }
 }

 void DFT()
 {
  //Given sequence of Numbers

  float[]  X = {1,2,3};
  float[]  Y = {2,3,5};
  float  N = X.Length;
  float re = 0;
  float im = 0;

  for (int k = 0; k < N; k++)
  {
      //The discrete Fourier transform, lists of Re & Im instead of a+ib
      for (int n = 0; n < N; n++)
       {
           float phi =  (Mathf.PI * k *n)/N;
           re += X[n] * Mathf.Cos(phi) - Y[n] * Mathf.Sin(phi);
           im -= Y[n] * Mathf.Cos(phi) - X[n] * Mathf.Sin(phi);
       }

      re = re/N;
      im = im/N;
      var  ampp = Mathf.Sqrt(re*re + im*im);
      var  phasse  = Mathf.Atan2(re,im);

      phase.Add(phasse);
      amp.Add(ampp);
  }
}

but answer is Not correct, I use Wolfram Mathematica to check the answer :


texts:
Dears,
I am facing a performance problem when I try to access cell 42 and 43 in XMMATRIX define in DirectXMath.h. The frames dropped by 100 FPS.

Here is my code:

for (int index = 0; index < m_CopyOfCascadeConfig.m_nCascadeLevels; ++index)
    {
        XMMATRIX mShadowTexture = m_matShadowProj[index] * dxmatTextureScale * dxmatTextureTranslation;

        XMStoreFloat4x4(&mShadowTextureFlt, mShadowTexture);

        // This is the line that cause the performance drop
        pcbAllShadowConstants->m_vCascadeOffset[index] =
            XMVectorSet(mShadowTextureFlt._41, mShadowTextureFlt._42, mShadowTextureFlt._43, 0.0);
}

I also tried to use the folowing but no hope:

pcbAllShadowConstants->m_vCascadeOffset[index] = mShadowTexture.r[3];

Any suggestes will be appreciated.


texts: Unity-Sharing values between functions invoked by buttons and the rest of the script

texts:
Ok so, here is the problem.

I am doing a multiplayer 2D game using UNET.

I have a script that kind of helps a player select an avatar to play with. The avatars are listed as a scrollview of buttons. These buttons invoke the function setAvatar(int id) that sets a player's avatar passing in an ID as argument. The function just sets the player's avatar using ID as index in a list of avatars.

Now the problem is this player is a prefab which is instantiated at the start of the playscene for Player A and Player B. So the setAvatar(int sprid) function assumes I am referring to the prefab whenever I use "gameObject"

So, I decided to store the local gameObject in a temporary variable.

Here's the full code,

public class Player2DController : NetworkBehaviour // Attached to player prefab
{
    public float moveForce = 2;
    Rigidbody2D myBody;
    Transform mainCamera;
    Shooting shscript;
    int i;
    public Transform joystick;
    GameObject temp;

    public Sprite[] spr;

    void Start ()
    {
        if (!isLocalPlayer)
        {
            Destroy (this);
            return;
        }

        temp = gameObject; // storing local gameobject in temp

        joystick = GameObject.Find ("MobileJoystick").transform;
        shscript = GetComponent<Shooting> ();
        mainCamera = Camera.main.transform;
        RotateCamera ();
        myBody = GetComponent<Rigidbody2D> ();

        if (isClient)
        {
            i = -1;
        }
        if (isServer)
        {
            i = 1;
        }

    }

    public void RotateCamera()
    {
        if (isClient)
        {
            mainCamera.rotation = Quaternion.Euler (new Vector3 (0f, 0f, 180f));
        }
        if (isServer)
        {
            mainCamera.rotation = Quaternion.Euler (new Vector3 (0f, 0f, 0f));
        }
    }

    void FixedUpdate ()
    {
        if (PauseMenu.isOn)
        {
            return;
        }
        Vector2 moveVec = new Vector2(CrossPlatformInputManager.GetAxis("Horizontal"),CrossPlatformInputManager.GetAxis("Vertical"))* moveForce;

        myBody.AddForce (moveVec * i);

        if (CrossPlatformInputManager.GetButton("Shoot"))
        {
            shscript.CmdFire ();
        }

    }

    public void setAvatar(int id) // called through the buttons in the avatar list
    {
        temp.GetComponent<SpriteRenderer> ().sprite = spr [id];//null pointer exception
    }
}

This code doesn't work. I get a null pointer exception on temp variable saying it is not assigned. But how can this be? I clearly assign it to active gameObject in Start() method. The only reason I can think of why this is happening is that since the button acts on the player prefab, it creates a separate instance of the script for the player prefab that doesn't get executed. So, when it invokes setAvatar(), it has a temp which is not initialized.

So that's the whole problem. Since this didn't work, I tried renaming the players as clientPlayer and serverPlayer and then accessing them using GameObject.Find(name).GetComponent<SpriteRenderer>().sprite. But this had no effect and no errors. I have no idea why.

So any ideas on how to go about this?


texts: Is it OK to use 6-7k texture map in Unity?

texts: I want to unwrap all my car into one texture (interier, wheels and e.t.c), so for better quality i need to use one big 7k texture. Is it OK or the better choice is to make smaller ones for groups ?


texts: How can I load assets dynamically on user's input in LibGDX HTML?

texts:
I am working with LibGDX and GWT and I am trying to publish my app as a HTML webapp, it has many assets with around hundred of folders, now I want to load them dynamically (user input is sent to JSNI, and security issues set aside), I want to be able to add more assets later without having to recompile the entire thing or creating new assets.txt file.
Here is how the app works. A user select a foldername from an HTML dropdown, this will trigger an javascript function created by JSNI: load(foldername). The app then load the files inside foldername and use it by accessing FileHandle file provided by Gdx.files.internal(file)
My goal is to be able to add more assets later on without recompiling/touching the java source code, and to eliminate load time so as not to preload hundreds of assets
I was unable to find similar problem anywhere on the Internet and I am fairly new to this field.
Workaround can be accepted too. I am using LibGDX 1.9.12 and GWT 2.8.2


texts: Open Source HTML/JS game(s) with license that would allow embedding in my app?

texts:
I'm working on an educational app for kids. At the end of the sign-up process, the kids must wait for a confirmation from their parents in order to gain access to the app.

While they wait for this to happen, we want to let the kid play a simple game as a way to keep their interest up.

Is there a marketplace or repository for games with such a license that we could either purchase (affordably) or use for free in our own app?


texts: view if GL_CULL_FACE is enabled/disabled

texts:
Im using GL_CULL_FACE, an i'm trying to map a key for enable/disable the gl_cull_face. Is there any posibility of viewing if it's enabled or not?
Thanks


texts: What is the simplest way to export a bezier curve created in Blender to a text file?

texts:
I have created a bezier curve in Blender.

I'd like to export this curve to a text file. What I need is :

Control point + handles, three points in total.

Example :

{{ 2.3333,4.3942, 55.333 }, { 0.3234, 2.4234, 4.0332 }, { 2.534, 6.S234, 12.0332 }}

I have tried to export the scene in Collada format but it doesn't seems to include curves information.

What is the easiest / simplest way to export this curve to some readable text file format ?


texts:
I'm working on a 2D side-scroller, OpenGL, pixel art. And I'm having trouble getting the pixels to remain square when scrolling the camera. By that I mean, when scrolling the camera at low speed when you have tile pixels being draw at 2x2 scale, you can see some pixels become 3x2 in size rather than 2x2. I've tried different ways of calculating the size of the orthographic projection in order to get the pixels sized correctly, and while they do usually appear correct when stationary, they always wobble while scrolling.

Here is my latest attempt at calculating window size for the orthographic projection:

#define TILE_SIZE 32 // Each tile is 32x32
#define TILE_MIN_HEIGHT 10 // Adjust pixel size to fit at east 10 tiles vertically in the window

float windowRatio = (float)window->width / (float)window->height;
int pixelSize = window->height / TILE_SIZE / TILE_MIN_HEIGHT;
float tileHeight = (float)window->height / (pixelSize * TILE_SIZE);
gameState->windowTileWidth = tileHeight * windowRatio * TILE_SIZE;
gameState->windowTileHeight = tileHeight * TILE_SIZE;

window->orthoProjection = matrix44_createOrthographic2D( gameState->windowTileWidth, gameState->windowTileHeight );`

So far, I've tried all of these in an attempt to eliminate the wobble:

Calculate orthographic projection as above, to fix at least 10 tiles vertically, adjusting projection size to fit window ratio.
Calculate orthographic projection to exactly fit a 20x10 tile scene, scaling pixels to fit window.
Render the scene to a 1:1 scale framebuffer, then blit that buffer to the window to scale it up to desired pixel size.
Disable offsetting of texture coordinates (I draw tiles from a texture atlas, and so offset the coordinates by 0.001 inside each quad to eliminate bleed from surrounding textures).

None of these have eliminated the wobbling. Sometimes it is extremely subtle, but still present when examining the movement closely.

What is the correct way to draw a 2D image to the scree with perfect square pixel accuracy, at a given pixel size?


texts:
I am making a TD game in unity, Initially I made all of my enemy movements frame rate dependent say:

I had a grid point1 at -22.65 and other at -21.1, diagrammatically:

(-22.65) _________(-21.1)_______(-21.1+1.55) ......

so the distance on x axis between two points is 1.55, divided it by 25 jumps with each enemy jump of 0.062 of each frame. On reaching on next point of grid the enemy find again its path. All went fine until I have requirement of FastForward and Pause feature. I used timeScale property of unity but it wont work as they are frame dependent. I also tried double speed of enemy on clicking fast forward button at any time, it has some issues that enemy jumps are now less and it fails to reach on next grid point.

Could someone suggest me solution to my problem. Do I need to change the enemy movement code to make it frame independent ?? I need the enemy to reach on the grid specific point I also need later to slow down any one enemy's speed when tower fires on it. Thnx


texts: How to create endless scrolling landscape using coco2d's CCParallaxNode

texts:
I created a horizontally scrolling landscape using CCParallaxNode. However it does not seem to support endless scrolling in one direction. As soon as the first image "ends" the background shines through. Adding an unlimited number of images is of course not an option. I thought about the usual way, namely adding two sprites for each parallax layer next to each other, and simply moving one at the end of the other at the appropriate time.

However, I have two issues:

parallax child nodes can't seem to be
re-positioned
the position of the child nodes vs
how far they have moved seem to be in
no relation to the parallax factor

This is how I set up the parallax node using 4 sprites with identical horizontal width:

CGPoint topOffset = CGPointMake(0, screenSize.height);
CGPoint midOffset = CGPointMake(0, screenSize.height / 2);
CGPoint downOffset = CGPointZero;

// Create a parallax node and add the sprites to it.
CCParallaxNode* paraNode = [CCParallaxNode node];
[paraNode addChild:para1 z:1 parallaxRatio:CGPointMake(0.5f, 0)
positionOffset:topOffset];
[paraNode addChild:para2 z:2 parallaxRatio:CGPointMake(1, 0) positionOffset:topOffset];
[paraNode addChild:para3 z:4 parallaxRatio:CGPointMake(2, 0) positionOffset:midOffset];
[paraNode addChild:para4 z:3 parallaxRatio:CGPointMake(3, 0) positionOffset:downOffset];
[self addChild:paraNode z:0 tag:ParallaxSceneTagParallaxNode];

Did anyone succeed in using CCParallaxNode for seamlessly endless scrolling?


texts: How to Initilize CCPoint Array from String?

texts: I've got string like this: {{0,168},{20,20}}, here indicates two points. I want to get them out to initialize my CCPoint. Do you guys know how to convert this?


texts: How can I smoothly move from tile to tile?

texts:
I've looked at other games with tile based movement. I am aiming to create a game like pokemon, where the player moves smoothly to the next tile.

I am using KeyAdapter, in my KeyInput class. This basically just sets a move speed which is added to the x position of my player in the player's tick function:

if(key == KeyEvent.VK_A && ((Player)object).velY == 0){
    object.setVelX(-3);
    ((Player)object).setDirection(Direction.LEFT);
}
//The other keys as well...

In my tick method, as I said it basically just adds it:

public void tick() {
    x += velX;
    y += velY;
}

And it renders in my render method through Awt Graphics. Anyways, I was wondering how I could make this have tile based movement. Each tile is 32x32 pixels. I've looked at other tutorials and they all seem to have different solutions, I'm not sure it will be compatible with what I'm using a KeyAdaptor. I assume I might have to use a modulus operator to make sure the movement is in tiles.


texts: Implementing a wheeled character controller

texts:
I'm trying to implement Boxycraft's character controller in XNA (with Farseer), as Bryan Dysmas did (minus the jumping part, yet).

My current implementation seems to sometimes glitch in between two parallel planes, and fails to climb 45 degree slopes. (YouTube videos in links, plane glitch is subtle).

How can I fix it? From the textual description, I seem to be doing it right.

(Note: my coordinates system is top for positive Y).

Here is my implementation (it seems like a huge wall of text, but it's easy to read. I wish I could simplify and isolate the problem more, but I can't):

public Body TorsoBody { get; private set; }
public PolygonShape TorsoShape { get; private set; }
public Body LegsBody { get; private set; }
public Shape LegsShape { get; private set; }
public RevoluteJoint Hips { get; private set; }
public FixedAngleJoint FixedAngleJoint { get; private set; }
public AngleJoint AngleJoint { get; private set; }

...

this.TorsoBody = BodyFactory.CreateRectangle(this.World, 1, 1.5f, 1);
this.TorsoShape = new PolygonShape(1);
this.TorsoShape.SetAsBox(0.5f, 0.75f);
this.TorsoBody.CreateFixture(this.TorsoShape);
this.TorsoBody.IsStatic = false;

this.LegsBody = BodyFactory.CreateCircle(this.World, 0.5f, 1);
this.LegsShape = new CircleShape(0.5f, 1);
this.LegsBody.CreateFixture(this.LegsShape);
this.LegsBody.Position -= 0.75f * Vector2.UnitY;
this.LegsBody.IsStatic = false;

this.Hips = JointFactory.CreateRevoluteJoint(this.TorsoBody, this.LegsBody, Vector2.Zero);
this.Hips.MotorEnabled = true;
this.AngleJoint = new AngleJoint(this.TorsoBody, this.LegsBody);
this.FixedAngleJoint = new FixedAngleJoint(this.TorsoBody);

this.Hips.MaxMotorTorque = float.PositiveInfinity;
this.World.AddJoint(this.Hips);
this.World.AddJoint(this.AngleJoint);
this.World.AddJoint(this.FixedAngleJoint);

...

public void Move(float m) // -1, 0, +1
{
    this.Hips.MotorSpeed = 0.5f * m;
}


texts: Is it possible to use mipmaps with dynamic textures in Dirext 11?

texts: I was trying create a texture with D3D11_USAGE_DYNAMIC and MipLevels equal to 0 (to create all the mip levels).  However, the texture failed to be created.  Is it possible to use mipmaps with dynamic textures?


texts: How can I roll up a plane with a vertex shader?

texts:
I have plane that I want to roll up using a vertex shader, like this:

I found a math demo that shows the kind of curve I want my mesh to follow. I tried implementing this in my shader code, but the results don't form a roll as expected:

Shader " Custom/Rolling "
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" {}
_Bend("Bend",Float) = 1
_Strength("Strength",Float) = 1
}

SubShader
{
Tags {"Queue"="Geometry" "IgnoreProjector"="true" "RenderType"="Opaque"}
Cull Off

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"

struct v2f
{
half2 texcoord  : TEXCOORD0;
float4 vertex   : SV_POSITION;
};

sampler2D _MainTex;
float _Bend;
float _Strength;

v2f vert(appdata_full v)
{
v2f o;

//I don't know what should I write here for rolling ,please help me.
//v.vertex.y *= ???
v.vertex.y *= exp(_Bend+(v.vertex.x*_Strength)); // something like this but this hasn't twist effect
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = v.texcoord;
return o;
}

float4 frag (v2f i) : COLOR
{

float2 uv = i.texcoord.xy;
float4 tex = tex2D(_MainTex, uv);

return tex;
}
ENDCG
}
}
Fallback Off
}

Instead of a neat roll, the end of my plane shoots up into the sky!


texts: Recognize pattern in 3D building environment

texts:
I'm currently developing 3rd person building game (as bacheleor thesis). I need to recognize constructed patterns co I can mark corresponding structure as some building (so player can start using that building).

I have folowing rules:

3 types of building blocks (all based on cube) (and in future there will be more types)
any block can be scaled up to k multiple in each axis (k = 20)
blocks can be rotated by any axis (but stays in 3D grid)

  Problem definition:
  4 cubes of base size (1,1,1) in a grid 2x2 should be equivalent to 1
  box size (2,2,1), so all possible variants (mainly different in rotation) could be evaluated as valid pattern construction.

I expect that my patterns will be up to 30x30x30 multiple of base size.

For example, I'd like to recognize structure like this: (currently placed in level by hand)

Size is 21x21x22 and it is constructed from multiple objects.

As a limitation, I will border pattern search from exact point (lets say control console for that structure). Current limitation constant is around 50x50x50 multiple of base cube. (Limit is subject to change based on answers here.)

I searched over 20hrs and result was only papers to recognize 3D structure from 2D image or recognize exact structure in 2D.

  My problem is that with growing K( each X,Y,Z) there is exponencially growing number of structures, which should be accepted as correct pattern construction.

  Question: What algorithm (+ heurestic) should I use?

EDIT: following 3 images contains visualization of structures, that are considered as correct variant of pattern at image 4, thus they should be found and accepted.

All together has same final shape (and has same material at same places). I simplified the problem only to 2D shape, but extending in 3D space is obvious.

Thank you for all answers / comments.


texts:
I've been trying to implement a 3D (with the Y axis being utilized) fog of war system similar to what XCOM uses.

There is only one hint that really seems to nail it, but I can't read the actual function that was in place.

http://etiennecarrier.com/zombie-tycoon-2-fog-of-war-shader/

The key difference here is that I'm also trying to apply this to a multi leveled building.

So the question is... How do you go about implementing a height based fog shader, with a masking texture to prevent it from drawing in certain world spaces.


texts: LibGDX - how to change FreeType Font color and screen coordinates

texts:
How can I change my FreeType Font color? I want to set custom color. I tried do this by using Color color = new Color() but don't work.

And second: can I change my screen coordinates? I use two different cameras. First camera for game and second for text. When I draw text in the (0,0) position, my text is in the center of the screen but I want to have (0,0) in the lower left corner. How do that?


texts: How to Show Daily Notification Using Libgdx Alarm Manager?

texts:
In a game written in Libgdx, I want to show users some daily notifications with the help of alarm manager.
These notifications will be independent of Firebase. In other words, I will not send the notification, it will be automatically shown to the user once every 24 hours.
Not required with alarm manager. Could you please tell if there is a different and easy way?


texts: How should player be able to hear 2D spatial sound?

texts: Let's say there is a multiplayer 2D game and a 2D spatial sound system, in which sound volume decreases, when distance to the sound position increases. E.g. explosion happens. Should player hear it if it's outside the camera's viewport zone? Basically, how big should a max distance to sound position should be? How is it handled in other 2D games?


texts: Java - Load new classes from a folder automatically at startup

texts:
I want to make my game-coding very flexible; so I wanted to make the game automatically load new Mobs from a folder named "mobs".

This must be only at startup; not while it's already running.

I just want to put a file with a name like "mouse.jar" (or others -> dynamic) into this folder, and the game should load it at startup.

I already saw this in "Robocode" (Robots) and "MCForge" (whole Mods), so it must be possible.

Can anyone tell me, how is it possible to load classes as resources in game at startup, regardless of the quantity?


texts: I imported a blend file into unity which contained 3 animations but I can only see one [Unity] and I need three

texts:
I can only see one in unity:
But there are three in blender:
I thank thee answers.


texts: When an object is launched off-screen, is there any way to know if it's coming back?

texts:
In this scene, the object becomes invisible and then comes back

In this scene, the object becomes invisible but does not come back

Is there any way I can tell if an object will come back when it becomes invisible?
Edit:
Thank you to S. Tarık Çetin for the solution
     private void Update()
     {
         if (isInvisible)
             if (IsNotComingBack())
                 OnInvisible?.Invoke();
     }

     private void OnBecameInvisible()
     {
         isInvisible = true;
     }

     private bool IsNotComingBack()
     {
         var pos = _cam.WorldToViewportPoint(_rb.position);
         var extents = _cam.WorldToViewportPoint(_spriteRenderer.sprite.bounds.extents);
         var isNotComingBack = pos.x + extents.x < 1 || pos.x - extents.x > 0;
         return isNotComingBack;
     }


texts: Looking for a peer reviewed article that details the benefits of a physics simulation within interactive media

texts:
I'm hoping this is the correct place to ask this question as it is video game related and can be seen as a key ingredient in modern game development.

Does anyone know of a peer reviewed article that details the benefits of incorporating a physics simulation into interactive media (such as video games)?

I can find books with a few remarks in their introduction (no more than a couple of sentences) but nothing substantial.


texts: Finding relative x and y value on a sprite [Gamemaker]

texts:
I'm having a little conundrum that may just result from a lack of knowledge of Gamemaker's functionality. I've attached two images to aid explanation.

I have a sprite of a turret (with a gun barrel), attached to a turret object, and at certain points in gameplay this object will spawn another object on top of it (let's call it the 'bullet object').

I would like the bullet object to spawn at the x and y coordinates at the end of the gun barrel. This would be easy to find as a pair of coordinates if the sprite was always stationary, in this configuration. Alas, it is not. It rotates like billy-oh. This means that the x and y coordinates at the end of the gun barrel are constantly different.

How do I find this constantly changing x and y coordinate? I imagine (though am most likely wrong) that there the initial x and y coordinates of the sprite are saved and can be found even if rotated; is there a function that does this? Or do I need to write a script and then call it every time I want to spawn the bullet object?

Thanks for your help.


texts: Most efficient way to draw vertex with OpenGL

texts:
I am writing an OpenGL 3D game.  There will be tons of triangles for terrain and objects in use.

I am studying from the OpenGL official guide and the first presented method is to call a function glVertex after the glBegin for each vertex you want to draw.

However this method sounds quite antique and inefficient when you have to draw thousands of triangles. I guess there are methods to store in the graphic card memory the information that does not change at every frame so that when you render each frame that information is already there. While for more "unstable" information probably you have to send new vertex data every frame and so a different tecnique might be more efficient.

Coming to my question: I would like a clear explanation of the most modern and efficient OpenGL functions and tecniques used to send vertex information to the hardware and to give instruction to render.

What are the best ways and OpenGL tools to send the order to render vertex data that seldom changes during the frames (i think of terrain and objects) and what it the best way to send vertex data that changes a lot during frames?


texts:
It's not stated in the documentation, so I'd like to ask if anyone knows if it's ok to halt a channel (via Mix_HaltChannel()) that's been already halted?

I'm asking 'cause I'd like to halt every channel with Mix_HaltChannel(-1)(which could possibly include already halted channels) before freeing the chunks for safety reasons, because the documentation states that it's not good to free chunks of channels that are still playing.

Thanks a lot in advance.


texts: hosting a windows game on a linux server

texts: there! I am currently working on a game on Unreal 4, and although im still in early production(barely any code written, mostly visual assets at this point), i want to ask this now, so that i know how to organize my work schedule. If the game it self is running on windows, can the games multiplayer server be on a linux machine? If possible will there be any complications during coding or setup that i need to look into? would very much apreciate any help. :)


texts: GLSL Fragment shader lighting lambert term

texts:
Just a simple question:
Should I or should i not normalize the SurfaceToLight vector to calculate the lambert term on a GLSL lighting shader?

I mean, here:

vec3 CalculateLights ( void )
{
vec3 OverallResult = (AmbientLight.Color * AmbientLight.Intensity * Material.Ambient.xyz );
vec3 SurfaceToCamera = WorldFragPosition - CameraPositionWorld;

// Apply point lights
for ( int LightIndex = 0; LightIndex < PointLightCount; ++LightIndex )
    {
    vec3 LightResult = vec3 ( 0, 0, 0 );
vec3 SurfaceToLight = PointLights[LightIndex].Position - WorldFragPosition;

float Distance = length ( SurfaceToLight );
if ( Distance > PointLights[LightIndex].Cutoff )
    continue;

// Calculate normalized vectors and Lambert term
vec3 NormalizedFragVertexNormalWorld = normalize( fragVertexNormalWorld );
vec3 NormalizedSurfaceToLight = normalize( SurfaceToLight );
//  float LambertTerm = max( dot( NormalizedSurfaceToLight, NormalizedFragVertexNormalWorld ), 0 ); // Should I use normalized here?
float LambertTerm = max( dot( SurfaceToLight, fragVertexNormalWorld ), 0 ); // Should I use normalized here?

// Compute the diffuse term.
vec3 DiffuseResult = LambertTerm * PointLights[LightIndex].Intensity * PointLights[LightIndex].Color * Material.Diffuse.xyz;
LightResult += DiffuseResult;

// Compute specular
//  float SpecularCoefficient = 0.0;
//  if ( LambertTerm > 0.0 )
//      SpecularCoefficient = pow ( max ( 0.0, dot ( SurfaceToCamera, reflect(-SurfaceToLight, NormalizedFragVertexNormalWorld))), Material.Shininess);
//  vec3 SpecularResult = SpecularCoefficient * Material.Specular.xyz * PointLights[LightIndex].Color;
//  LightResult += SpecularResult;

// Compute attenuation
float Attenuation = PointLights[LightIndex].ConstantAttenuation + PointLights[LightIndex].LinearAttenuation * Distance + PointLights[LightIndex].ExponentialAttenuation * pow ( Distance, 2 );

//  float Attenuation = 1.0 / (1.0 + PointLights[LightIndex].ConstantAttenuation * pow(Distance, 2));
LightResult /= Attenuation;
OverallResult += LightResult;
    }

return OverallResult;
}

As you can see, i've been trying out some different formulas on this shader. Specular still does not work.
Here is the normalized and non-normalized versions of the image


texts:
I want to be able to quickly outline sprites(mainly with black, but other colours too) without doing it manually, as pictured. What would be a good program/solution to do so?

Edit: I don't want it to happen at runtime, I just want to have the second version and I can scrap the first.


texts: Why won't PNGs load successfully to game from server?

texts:
I'm working on a game which involves loading pictures from a server and rendering them as sprites. The images are stored as PNGs and open normally from on the server. I get no errors when downloading. And as a test I saved the images to files and they seem to save properly.
But, when I try rendering the sprites in the game, Unity doesn't understand what they are and just shows red questionmarks. The sprites load fine if I try loading them from Resouces/Assets folder.
Here's how I'm downloading the pictures:
Using UnityWebRequest, images are downloaded as Texture2D objects, converted to PNGs and then saved to a static-class called GameData.
Here's what the code for the image download looks like:
foreach (String imgName in imgNames) {

        using( UnityWebRequest imgRequest =  UnityWebRequestTexture.GetTexture(pathName+imgName)) {

           yield return imgRequest.SendWebRequest();

         if(imgRequest.isNetworkError || imgRequest.isHttpError) {
             ...
         }

          else  if(imgRequest.isDone) {
            Texture2D texture = DownloadHandlerTexture.GetContent(imgRequest);
            byte[] spriteBytes = texture.EncodeToPNG();
            File.WriteAllBytes(Application.dataPath + "/debug_sprites/"+imgName+".png" , spriteBytes );
            var rect  = new Rect(0, 0, 8, 8);
            Sprite spriteS = Sprite.Create(texture, rect, new Vector2(0.5f,0.5f));
            GameData.SetImg(imgName, spriteS);

          }
          downloadStatus.text = "Downloading file "+ ++i +" of "+(imgNames.Count+audioNames.Count);
   }

The code for where the image is saved in GameData:
public static void SetImg(string imgName, Sprite img) {

             imgDict.Add(imgName, img);

}

And here's the code where the sprites are supposed to get rendered to the game:
firstImage = GameData.GetImg(choice1.text);
//firstImage = Resources.Load<Sprite> (choice1.text);
GameObject go = GameObject.Find ("ChoiceOneTarget");
SpriteRenderer spriteR = go.GetComponent<SpriteRenderer> ();
spriteR.sprite = firstImage;

Note: I've tried downloading both with and without the extension name, but it didn't change anything.


texts: MiniMax where bots make simultaneous moves .

texts: What is the correct approach for using miminax in a game where bots make simultaneous moves ?


texts: How to properly multi-thread my game loop?

texts:
I am trying to implementing multi-threaded game loop in iOS.
(Actually, two thread - Render and Update)

This is my structure.

Update Loop

Has logic and at the end of loop, save update state. (Basically copy buffer for Render)

Render Loop

Using CADsiplayLink
It is on Main
Everytime, it triggers method, get the state, and draw.

I am seeing some stuttering, and I am thinking render loop is just faster than update loop, and also inconsistent "Render" call, something like this:

Update #1     ->    Render #1
Update #2     ->    Render #1
Update #2     ->    Render #2

How can I synchronize this?

I heard that Render thread should be not on Main Thread, and I am using CADisplayLink with default setting. (Call MainLoop); is it running on Main thread? If running on different thread, is better, can I get some suggestions working with CADisplayLink? It could be that I just lack some understanding about CADisplayLink.

Is my current structure adequate? Could it be improved?


texts: Is it possible to convert from specular/glossiness to metallic/roughness textures for UE4?


texts: What algorithm can I use to detect simple shapes in a 4x4 matrix?

texts:
I'm working on a simple multiplayer game that receives a random 4x4 matrix from a server and extracts a shape from it.

For example:

XXOO       OXOO
XXOX       XXOO
XOOX  and  XOOO
XXXX       OXXX

So in the first matrix the shape I want to parse is:

  oo
  o
 oo

and the 2nd:

  oo
  oo
 ooo

I know there must be an algorithm for this because I saw this kind of behavior on some puzzle games but I have no idea how to go about to detecting them or even where to start.

So my question is: How do I detect what shape is in the matrix and how do I differentiate
between multiple colors? (it doesn't come only in X and O, it comes in a maximum of 4). Additionally, the shape must be a minimum of 4 blocks.


texts: Difference between methods - onClick.AddListener and On Click under UI button inspector?

texts:
Within my Unity Project in my code, (see below), I have a button called Check which executes when CheckPress() function is called. I read two approaches by which this can be done.
Appraoch 1: Using Check.onClick.AddListener(CheckPress); and then attaching script to Canvas. When I press run and click the Check button, this works.
Approach 2: The other approach I read is that, I can attach my script to Canvas. From there I select the button Check from hierarchy, then under inspector I see On Click(), I click + sign and then drag the Canvas and place it in Object (see the attached image), then under No Function I select the CheckButtonBehaviour Script and select the CheckPress(). When I press run and click the Check button, this also works as intended.
I wanted to know if these two approaches are same or different. If they are different, then in which context either approach should be implemented.
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Threading;
using UnityEditor;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System;
using System.Linq;

public class CheckButtonBehaviour : MonoBehaviour
{

public Button Check;
public Button Play;
public Button NextSignal;

public List<string> signals = new List<string> {"Speech1", "Speech2", "Speech3", "Speech4"};
public List<string> shuffledSignals = new List<string>();
public int index = 1;
public int counter = 3;

private static int localPort;
private string IP;
public int port = 8050;
IPEndPoint remoteEndPoint;
UdpClient client;

void Start()
{

    var rndr = new System.Random();
    shuffledSignals = signals.OrderBy(i => rndr.Next()).ToList();

    IP = "127.0.0.1";
    port = 8050;
    remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
    client = new UdpClient();
    Play.gameObject.SetActive(false);
    NextSignal.gameObject.SetActive(false);

    Check.onClick.AddListener(CheckPress);

}

public void CheckPress()
{

    byte[] data0 = Encoding.ASCII.GetBytes("starting"); ///OLD CODE part
    client.Send(data0, data0.Length, remoteEndPoint);
    Debug.Log("<color=blue>Something is sent to MAX</color> : starting");

    Check.gameObject.SetActive(true);
    Check.interactable = false;
    Check.enabled = false;

    Play.gameObject.SetActive(true);
    NextSignal.gameObject.SetActive(true);

}


texts: Collision in PyGame for spinning rectangular object.touching circles

texts:
I'm creating a variation of Pong. One of the differences is that I use a rectangular structure as the object which is being bounced around, and I use circles as paddles. So far, all the collision handling I've worked with was using simple math (I wasn't using the collision "feature" in PyGame). The game is contained within a 2-dimensional continuous space.

The idea is that the rectangular structure will spin at different speed depending on how far from the center you touch it with the circle. Also, any extremity of the rectangular structure should be able to touch any extremity of the circle. So I need to keep track of where it has been touched on both the circle and the rectangle to figure out the direction it will be bounced to.

I intend to have basically 8 possible directions (Up, down, left, right and the half points between each one of those). I can work out the calculation of how the objected will be dislocated once I get the direction it will be dislocated to based on where it has been touch. I also need to keep track of where it has been touched to decide if the rectangular structure will spin clockwise or counter-clockwise after it collided.

Before I started coding, I read the resources available at the PyGame website on the collision class they have (And its respective functions). I tried to work out the logic of what I was trying to achieve based on those resources and how the game will function. The only thing I could figure out that I could do was to make each one of these objects as a group of rectangular objects, and depending on which rectangle was touched the other would behave accordingly and give the illusion it is a single object. However, not only I don't know if this will work, but I also don't know if it is gonna look convincing based on how PyGame redraws the objects.

Is there a way I can use PyGame to handle these collision detections by still having a single object? Can I figure out the point of collision on both objects using functions within PyGame precisely enough to achieve what I'm looking for?

P.s: I hope the question was specific and clear enough. I apologize if there were any grammar mistakes, English is not my native language.


texts:
I am attempting to find the furthermost point in my game world given the player's current location and a normalized direction vector in screen space. My current algorithm is:

convert player world location to screen space
multiply the direction vector by a large number (2000) and add it to the player's screen location to get the distant screen location
convert the distant screen location to world space
create a line running from the player's world location to the distant world location
loop over the bounding "walls" (of which there are always 4) of my game world

check whether the wall and the line intersect

if so, where they intersect is the furthermost point of my game world in the direction of the vector

Here it is, more or less, in code:

public Vector2 GetFurthermostWorldPoint(Vector2 directionVector)
{
    var screenLocation = entity.WorldPointToScreen(entity.Location);
    var distantScreenLocation = screenLocation + (directionVector * 2000);
    var distantWorldLocation = entity.ScreenPointToWorld(distantScreenLocation);
    var line = new Line(entity.Center, distantWorldLocation);
    float intersectionDistance;
    Vector2 intersectionPoint;

    foreach (var boundingWall in entity.Level.BoundingWalls)
    {
        if (boundingWall.Intersects(line, out intersectionDistance, out intersectionPoint))
        {
            return intersectionPoint;
        }
    }

    Debug.Assert(false, "No intersection found!");
    return Vector2.Zero;
}

Now this works, for some definition of "works". I've found that the further out my distant screen location is, the less chance it has of working. When digging into the reasons why, I noticed that calls to Viewport.Unproject could result in wildly varying return values for points that are "far away". I wrote this stupid little "test" to try and understand what was going on:

[Fact]
public void wtf()
{
    var screenPositions = new Vector2[]
        {
            new Vector2(400, 240),
            new Vector2(400, -2000),
        };

    var viewport = new Viewport(0, 0, 800, 480);
    var projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, viewport.Width / viewport.Height, 1, 200000);
    var viewMatrix = Matrix.CreateLookAt(new Vector3(400, 630, 600), new Vector3(400, 345, 0), new Vector3(0, 0, 1));
    var worldMatrix = Matrix.Identity;

    foreach (var screenPosition in screenPositions)
    {
        var nearPoint = viewport.Unproject(new Vector3(screenPosition, 0), projectionMatrix, viewMatrix, worldMatrix);
        var farPoint = viewport.Unproject(new Vector3(screenPosition, 1), projectionMatrix, viewMatrix, worldMatrix);

        Console.WriteLine("For screen position {0}:", screenPosition);
        Console.WriteLine("   Projected Near Point = {0}", nearPoint.TruncateZ());
        Console.WriteLine("   Projected Far Point = {0}", farPoint.TruncateZ());
        Console.WriteLine();
    }
}

The output I get on the console is:

  For screen position {X:400 Y:240}:
     Projected Near Point = {X:400 Y:629.571 Z:599.0967}
     Projected Far Point = {X:392.9302 Y:-83074.98 Z:-175627.9}

  For screen position {X:400 Y:-2000}:
     Projected Near Point = {X:400 Y:626.079 Z:600.7554}
     Projected Far Point = {X:390.2068 Y:-767438.6 Z:148564.2}

My question is really twofold:

what am I doing wrong with the unprojection such that it varies so wildly and, thus, does not allow me to determine the corresponding world point for my distant screen point?
is there a better way altogether to determine the furthermost point in world space given a current world space location, and a directional vector in screen space?


texts: How Do I Play An Animation In Unity 5.3.4?

texts:
I am confused on how to play an animation with the new unity version because the flag "Automatically Play Animation" is gone.  I cant have the animation connected to my GameObject because it plays right away.

using UnityEngine;
using System.Collections;

public class FPSCamera : MonoBehaviour {

    public float lookSensitivity = 5;
    private float xRotation;
    private float yRotation;
    private float currentRotationX;
    private AnimationClip walking;

    void Start() {
        // DONT KNOW HOW TO FIND AND START WALKING ANIMATION CLIP
    }
    void Update() {
        yRotation += Input.GetAxis("Mouse X") * lookSensitivity;
        xRotation -= Input.GetAxis("Mouse Y") * lookSensitivity;
        xRotation = Mathf.Clamp(xRotation, -90, 90);
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
    }
}


texts: Effects to make a speeding spaceship look faster

texts:
I have a spaceship and I've created a "boost" functionality that speeds up my spaceship, what effects should I implement to create the impression of high speed?

I was thinking of making everything except my spaceship blurry but I think there would be something missing. Any ideas?

Btw. I am working in XNA C# but if you aren't familiar to XNA describing some effects is still useful.

The Game is 3d and i've attached some printscreens of the game

This is in normal mode ( none boosted )

and here is the boosted mode ( the craft speeds up forward while the camera speeds in its normal speed , the non boosted speed )


texts: I am making a GJK-EPA based collision detection routine. In this picture, the algorithm picks up on two contact points (the endpoints of the green penetration vector). I'm certain that the penetration vector (normal and depth) is correct, but the contact points seem to off by a translation - shouldn't they lie within the intersecting part?


texts: Unity Editor - Call a method from a ScriptableObject from its own custom Editor

texts:
I have a class like this:

public class NoiseMap : ScriptableObject
{
    public string Hello()
    {
        //...
    }
}

Now I am building its custom editor:

[CustomEditor(typeof(NoiseMap))]
public class NoiseMapEditor : Editor
{

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        // How to call Hello() ???

        serializedObject.ApplyModifiedProperties();
    }

}

I would like to get the value of the method Hello. How could I achieve this?


texts:
i'm wondering if there's any 2D AI source code or engines out there. I'm inspired by  the Euphoria engine, and want to use whatever is already out there to make something like it in 2D, where the characters can move left and right, and attempt to preserve themselves. The only new feature i would want to add on is ability to learn from common results after an action.

I'm thinking the way it would work is you attach some AI to a character, and it determines movement/detection based on the number of arms, legs, joints, restrictions, and other movement-related body parts.

anything relating to AI would probablly be helpful as i've never worked with it:

How do you guys suggest i get started? (Btw: i'm using box2D/ SFML at the moment)

oh yeah and preferably open source =)


texts:
I'm working on a 2D tile based game in which the player interacts with other game objects (chests, AI, Doors, Houses etc...). The entire map will be stored in a file which I can read. When loading the tilemap, it will find any tile with the ID that represents a gameobject and store it in a hashmap (right data structure I think?).

    private static HashMap<Integer, Class<GameObject>> gameObjects = new HashMap<Integer, Class<GameObject>>();

How exactly would I go about calling, and checking for events? I figure that I would just call the update, render and input methods of each gameobject using the hashmap.

Should I got towards a Minecraft/Bukkit approach (sorry only example I can think of), where the user registers an event, and it gets called whenever that event happens.

Or should I just loop through the entire hashmap looking for an event that fits?

I'm using Java and LWJGL.

Thanks waco


texts: Do I need to make network game fully deterministic to achieve a non-exploitable MOBA/RTS?

texts:
First of all - I know some networking concepts and I coded couple games with GDX/Kryonet/Unity/UNET. I've read all the Gaffer's, Gambetta's and Valve's, but still, can't decide which approach should I follow.

Network engineers say that for the game to be truly 'safe', we need a fully authoritative server. To shorten the definition:

  A fully authoritative client-server system is when the client sends
  the input only, and the server runs the physics.

There are exceptions to this. Client-side simulation these days is required to maintain a real-time experience. It's impossible to achieve a real-time smooth movement without the interpolation, extrapolation and other prediction mechanisms.

I've integrated a small UNET network, where I can move my players around with a click-to-move. The synchronization is made through the built in commands and transmissions (syncvars). I perform the logic myself in callbacks. To fix the jitter, I combined all the knowledge from the websites above and coded a buffer which is blocking enemies coordinates for 100ms so I have some data to interpolate them on the clients. It basically views the enemies 100ms in the past.

I know that modern RTS games networking mechanisms are far more advanced than just buffering & interpolation, but it should be enough to create a concept similar to DOTA/LoL/Diablo 3 smooth feel.

As far as I get it there are two approaches:

Authoritative Input - sending inputs, receives positions & own corrections so the client can fix wrong predicted values
Non-authoritative Input - sending Transform values (position, rotation).

The second approach is believed to be non-deterministic, not authoritative and way easier to implement. Comes with a risk of cheating.

Of course it does come with a risk, but the server is the one with a head here. He owns all the objects, he checks their movement speed, teleportation, everything and transmits the correct data to the rest of the crew, not the cheated one.

From the other point of view, the first approach with input safety applies only to deterministic-lockstep simulations. I don't really know if modern games use this approach (I read that Blizzard's HoTS does, Valve's CS does, but I'm not sure of MOBA's).

My question is:

Is this unwise/unprofessional to transmit positions/rotations/transforms from the client to the server even, when the server decides what to do with them and passes through anti-cheat mechanisms? Writing a simple anti-speed/teleport hack seems a way easier than fighting with floating point determinism and making the server & client's simulations fully equal.

Is there something I'm missing?


texts: Naming conventions for external resources?

texts:
While we develop games, then we have utilize several external resources, for example

Image
Sound
Animation
Sprite Sheet

Is there any good naming convention regarding these external resources?


texts: Will I have an easier time learning OpenGL in Pygame or Pyglet? (NeHe tutorials downloaded)

texts:
I'm looking between PyGame and Pyglet, Pyglet seems to be somewhat newer and more Pythony, but it's last release according to Wikipedia is January '10. PyGame seems to have more documentation, more recent updates, and more published books/tutorials on the web for learning.

I downloaded both the Pyglet and PyGame versions of the NeHe OpenGL tutorials (Lessons 1-10) which cover this material:

lesson01 - Setting up the window
lesson02 - Polygons
lesson03 - Adding color
lesson04 - Rotation
lesson05 - 3D
lesson06 - Textures
lesson07 - Filters, Lighting, input
lesson08 - Blending (transparency)
lesson09 - 2D Sprites in 3D
lesson10 - Moving in a 3D world

What do you guys think? Is my hunch that I'll be better off working with PyGame somewhat warranted?


texts: Organizing scene graph nodes that have multiple parents

texts:
I am trying to understand how, from an abstract sense, scene graphs should be organized.

Say that in a game, there is a scene where the user is inside a house. The house has four walls, and on one wall there is a painting. There is also a wood stove resting on the ground but with an exhaust pipe that extends up and "through" the ceiling. Also on the floor, there is a table with a pen and a piece of paper on it. How might this particular scene graph be organized?

house/
    wall_1/
    wall_2/
        painting
    wall_3/
    wall_4/
    floor/
        table/
            pen
            paper
        woodstove
    ceiling/

Here's the root of my question: the wood stove connects to both the floor and the ceiling, so which parent node should it be a child of?


texts: What is OpenGL ES Shading Language based on and what are the differences?

texts:
My guess is that it is derived from version 1.10 of the OpenGL Shading Language, document revision number 59. Found it here, page 7:
http://old.siggraph.org/publications/2006cn/course16/KhronosSpecs/ESLanguageSpec1.10.11.pdf
The differences are also listed there with underlined text.

Can anyone confirm that it is based on version 1.10?

I took a look into the latest revision of OpenGL ES Shading Language - 1.0.17. It seems there is no reference to the original OpenGL Shading Language and no difference specs at all. The problem is that I can't find any document revisions between 1.10.11 and 1.0.17. They could change their mind and derive ES Shading Language from Shading Language 1.20. or something else.


texts:
I'm trying to make Mario so im trying to do the collision part but whenever I do the side collision it bounces back too far. I want to make it so that it only stops Mario not bounces him back.

        public void MarioBrickCollide()
    {
        for (int collide = 0; collide < brick.Length; collide++)
        {
            if (Mariovec.Y <= brickvec[collide].Y && Mariovec.Y + Mario.Height + 3 > brickvec[collide].Y && Mariovec.X + Mario.Width > brickvec[collide].X && Mariovec.X < brickvec[collide].X + brick[collide].Width)
            {
                Mariovel.Y = 0;
                brickHitTop = true;
            }
            if (Mariovec.X + Mario.Width >= brickvec[0].X && Mariovec.X < brickvec[0].X + brick[0].Width && Mariovec.Y + Mario.Height > brickvec[0].Y && Mariovec.Y < brickvec[0].Y)
            {
                Mariovec.X = brickvec[collide].X - Mario.Width;
            }
        }
    }

What can I do to make the collisions work?


texts: Something orbital rotation is happening when I added player movement

texts:
I think this is happenning because of my player movements which is this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;

    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Horizontal");

        Vector3 move = new Vector3(x, 0f, z);
        GetComponent<Rigidbody>().AddForce(move * speed);
    }
}

When ever I rotate my camera, the player is moving as well like in an orbital rotation I can't explain it so I made a video.
This is my camera movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMovement : MonoBehaviour
{
    public Transform head;
    public Transform container;
    public float mouseSensitivity;
    float xRotation = 0f;

    private void Start() {
        Cursor.visible = false;
        Cursor.lockState = CursorLockMode.Locked;
    }

    private void Update() {
        float mouseX = Input.GetAxis("Mouse X") * Time.deltaTime * mouseSensitivity;
        float mouseY = Input.GetAxis("Mouse Y") * Time.deltaTime * mouseSensitivity;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.position = head.position;
        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        container.Rotate(Vector3.up * mouseX);
    }
}

I think this is bugging because I am suppose to rotate the Player only not the whole container? This is my player container setup:

I put the player movement on the player object, camera movement on the camera (not the main camera)


texts:
My WWW requests are returning an error that is empty since I switched my project to 2017. Anyone experiencing the same or have a solution?

void Start()
  {
    StartCoroutine(RetrieveQuests());
  }

IEnumerator RetrieveQuests() {
  WWW www;
  www = new WWW("URL that I dont want to share here.");
  yield return www;
  if (www.error != null) {
    Debug.Log("There was an error sending request: " + www.error);
  } else {
    Debug.Log(www.text);
  }
}

I get the following log when I run it: "There was an error sending request: ", which means www.error is empty but there is an error.

NOTE: This does work on earlier versions of Unity.