texts: Calculating Minimum Translation Vector in Separating Axis Theorem based algorithm

texts:
In the 2D SAT collision determination algorithm, you project the convex polygons onto each potential separating axis. Supposing the polygons intersect, from what I understand, the axis for which the overlap of the projections is the smallest determines the minimum translation vector. The MTV direction is parallel to the separating axis and the magnitude is the length of the overlap.

When calculating the overlap, however, I'm wondering if it is necessary to account for different overlap scenarios.

We have projection intervals (for some axis) (a, b) and (c, d). (a, b) comes from the polygon who normals we're currently testing as separating axes.

Case 1:

Case 2:

Intuitively, the overlap in the first case is b - c, and the overlap in the second case is d - a. And if this turns out the be the axis of minimum overlap, you might want to flip the MTV direction in one of the above cases, depending on what you are doing.

However, I'm wondering if it is actually necessary to consider the d - a interval. I.e., is there a proof of something to the effect that, when d - a is less than b - c, that the axis cannot possibly be the axis of minimum overlap (or, if it is, that we could have used another edge's normal, such that its projections' b - c interval was the minimum overlap)? In the second case, it is true -- d - a is less than b - c, and there is a smaller axis of overlap (e.g. b - c when the axis is the red polygon's upper edge normal).

But does this hold in general? Is there a simple counter example?


texts: What rendering techniques would I use to draw a drop shadow effect for cards in a card game?

texts:
What type of shading algorithm might be used to create shadows like these?

the one I'm making is similar but it is all done with a 2D drawing API powered by OpenGL so there is no Z coordinate.

In addition, for the hand itself, I'd really like to get a shaded feel like seen here:

I'm just not sure how to achieve a shaded look close to that.

The number of cards is bound to change and the cards get thrown onto the table so I can't use any type of light map of sorts.

What sorts of algorithms should I look into (aside from blur which I know 'll need to do?)

Thanks

Update

I'm making a 2D card game. I want to add dropshadows offset from the cards, a bit like:

The way I'm thinking of doing it is:

Keep a texture that is the same size as the backbuffer.
Draw dark rectangles as makeshift cards to that texture.
Blur that texture.
Draw my cards to that texture.
Do additional lighting on the cards.
Draw this texture to the backbuffer.

My questions are:

Is this the right way to do this?
Is there a way to do it without render to texture (keeping a bitmap
as big as the backbuffer)?
Is it safe to assume that the maximum texture size will not be
exceeded by the backbuffer size? (What I mean is, if the backbuffer
is 2000x3000, then is it safe to say that I can create a texture in
video memory of that size?

Thanks


texts: How do I handle collision detection so fast objects are not allowed to pass through walls?

texts:
I'm creating a 2d sidescrolling shooter, and I'm having a little trouble with collision detection for the bullets. Everything including the bullets are objects with their own polygons / update methods.

The trouble is that bullets go fast, and at 60 frames per second (what the game runs at) a bullet will often skip right through a wall -- since it moves more than the width of the wall during in the update interval -- and continue happily on its way since the polygons will never actually overlap.

What can I do about this? The only thing I've been able to come up with is to draw a line from the old position to the new position and do collision detection on that, but line drawing for collision detection is recommended against by the slick2d documentation. How can I solve this?


texts: Ensuring that a randomly generated galaxy wont place stars inside one another?

texts:
I'm attempting to build a game with a spiral galaxy design. In doing so I followed a short guide on making the rough layout of the galaxy.

My code works, but the "stars" (I'm bad with variable names, in this code "star" refers to the central star of a solar system) often clip into one another. Is there a way for me to ensure that no stars will intersect?

Code below is what I'm using to generate my galaxies.

    for(var i = 0; i < starCount; i++) {
    var distance : float = Random.Range(minDistance, maxDistance);
    distance = Mathf.Pow(distance, 2);

    // Choose an angle betweeen 0 and 2*PI
    var angle : float = Random.Range(0.0 , 1.0) * 2 * Mathf.PI;
    var armOffset : float = Random.Range(0.0,1.0) * armOffsetMax;

    armOffset = armOffset - armOffsetMax/2;
    armOffset = armOffset * (1/distance);

    var squaredArmOffset : float = Mathf.Pow(armOffset, 2);
    if(armOffset < 0) {
        squaredArmOffset = squaredArmOffset * -1;
    }
    armOffset = squaredArmOffset;

    var rotation : float = distance * rotationFactor;

    angle = Mathf.Round(angle/armSeparationDistance) * armSeparationDistance + armOffset + rotation;

    //Convert polar coordinates to 2D cartesian ones
    var starX : float = Mathf.Cos(angle) * distance;
    var starY : float = Mathf.Sin(angle) * distance;

    var randomOffsetX : float = Random.Range(0.0, 1.0) * randomOffsetXY;
    var randomOffsetY : float = Random.Range(0.0, 1.0) * randomOffsetXY;

    starX += randomOffsetX;
    starY += randomOffsetY;

    var newStar : Transform = Instantiate(star, Vector3(starX, starY), Quaternion.identity);
    newStar.transform.parent = center;
}


texts: Collision detected on only the latest added tile

texts:
I'm making a 2D platformer and I'm using tiles as the ground. I have a Tile class and I'm loading the tiles with the help of a list in the main game class:

public static List<Tile> tiles = new List<Tile>();

The following is how I load the tiles from the list with 2 for loops in the LoadContent method:

for (int i = 0; i<=20; i++)
            tiles.Add(new Tile(Content.Load<Texture2D>("tile"), new Vector2(i * 16, 304)));
        for (int i = 0; i <= 10; i++)
            tiles.Add(new Tile(Content.Load<Texture2D>("tile"), new Vector2(i * 16, 288)));

Now, I wanna apply some kind of gravity and collision, still it's just something primitive. I'm applying these inside a Player class within a foreach loop like this:

foreach (Tile tile in Game1.tiles)
        {
            if (isInAir == true) { velocity.Y = 100f; }
            else { velocity.Y = 0f; }

            if (recBot.Intersects(tile.rectangle)) colBot = true;
            else colBot = false;
        }

        if (colBot == true) isInAir = false;
        else isInAir = true;

The issue is that the collision occurs only on the last loaded tile by the for loop in the LoadContent method. The sprite stops falling when it collides with the last added tile, but when I'm moving left or right and it intersects with other tiles, it doesn't apply the collision and it falls through them.

I'm kinda new to programming, so take me easy :) Any other things that you need to know, just tell me and I'll add more details or code!


texts: Send Messages in Update Function Button UI Unity 5

texts:
I've been working on a project where i need to fulfill the following behaviors:

1) when clicking anywhere in the screen the character should do something

2) there are some buttons so except when you click a UI Button (which is the pause button in this case )you should move.

So, the problem is since the character behavior is in the Update Function when the player clicks on the pause button unity executes first the Update function, moves the character and pauses after that.

Is there any way to pause tell Unity to execute first the OnClick function inside the UI Button than the Update function?

What i tried was this but it didn't work:

1)do 2 booleans click1,click2;

2)click1 equals true when we click anywhere in the screen

3)click2 equals true when we click on the UI Button

4)then i do something like this so unity should wait 1 frame before executing the movement when click1 == true && click2 == false, we execute the behavior else that means we hit the UI button.

This is how it looks in actual code

void Update()
{
    if (platform == RuntimePlatform.WindowsEditor || platform == RuntimePlatform.WindowsPlayer)
                {
                    Debug.Log("1");
                    if (v_click1 == true && v_click2 == false)
                    {
                        if (v_inGround)
                            v_changeGravity = ChangeGravity();
                        Debug.Log("2");

                        v_click1 = false;//reset the value
                    }
                    if (Input.GetMouseButtonDown(0))
                    {
                        Debug.Log("3");

                       v_click1 = true;
                    }
                }
}

As you can see i have logged some numbers and Number 4 is not there but it displays when Onclick function sends the message from the UI Button.

The order this is taking is the following:

1

3 we detect a click which is in the button but we dont know that

2 we do the behavior(movement)

4 the function for pause gets called...

So, this is basically the problem is there any way to do this or should i just try not using the UI?

if the question is too confusing i will try to rephrase it haha.

Thanks!!


texts: Space-efficient data structures for broad-phase collision detection

texts:
As far as I know, these are three types of data structures that can be used for collision detection broadphase:

Unsorted arrays: Check every object againist every object - O(n^2) time; O(log n) space. It's so slow, it's useless if n isn't really small.

for (i=1;i<objects;i++){
  for(j=0;j<i;j++) narrowPhase(i,j);
};

Sorted arrays: Sort the objects, so that you get O(n^(2-1/k)) for k dimensions O(n^1.5) for 2d and O(n^1.67) for 3d and O(n) space.

Assuming the space is 2D and sortedArray is sorted so that if the object begins in sortedArray[i] and another object ends at sortedArray[i-1]; they don't collide
Heaps of stacks: Divide the objects between a heap of stacks, so that you only have to check the bucket, its children and its parents - O(n log n) time, but O(n^2) space.

This is probably the most frequently used approach.

Is there a way of having O(n log n) time with less space? When is it more efficient to use sorted arrays over heaps and vice versa?


texts: How can I cull non-visible isometric tiles?

texts:
I have a problem which I am struggling to solve. I have a large map of around 100x100 tiles which form an isometric map. The user is able to move the map around by dragging the mouse. I am trying to optimize my game only to draw the visible tiles.

So far my code is like this. It appears to be ok in the x direction, but as soon as one tile goes completely above the top of the screen, the entire column disappears. I am not sure how to detect that all of the tiles in a particular column are outside the visible region.

    double maxTilesX = widthOfScreen/ halfTileWidth + 4;
    double maxTilesY = heightOfScreen/ halfTileHeight + 4;

    int rowStart = Math.max(0,( -xOffset / halfTileWidth)) ;
    int colStart = Math.max(0,( -yOffset / halfTileHeight));

    rowEnd = (int) Math.min(mapSize, rowStart + maxTilesX);
    colEnd = (int) Math.min(mapSize, colStart + maxTilesY);

EDIT - I think I have solved my problem, but perhaps not in a very efficient way. I have taken the center of the screen coordinates, determined which tile this corresponds to by converting the coordinates into cartesian format. I then update the entire box around the screen.


texts: Problems when rendering code on Nvidia GPU

texts:
I am following OpenGL GLSL cookbook 4.0, I have rendered a tesselated quad, as you see in the screenshot below, and i am moving Y coordinate of every vertex using a time based sin function as given in the code in the book.

This program, as you see on the text in the image, runs perfectly on built in Intel HD graphics of my processor, but i have Nvidia GT 555m graphics in my laptop, (which by the way has switchable graphics) when I run the program on the graphic card, the OpenGL shader compilation fails.

It fails on following instruction..

pos.y = sin.waveAmp * sin(u);

giving error>>
Error C1105 : Cannot call a non-function

I know this error is coming on the sin(u) function which you see in the instruction.
I am not able to understand why?
When i removed sin(u) from the code, the program ran fine on Nvidia card.
Its running with sin(u) fine on Intel HD 3000 graphics.

Also, if you notice the program is almost unusable with intel HD 3000 graphics, I am getting only 9FPS, which is not enough. Its too much load for intel HD 3000.

So, sin(X) function is not defined in the OpenGL specification given by Nvidia drivers or something else??


texts: XNA Why is Texture.GetData one dimensional?

texts: This is question has been really killing me. In XNA when you want to convert an image to color data using Texture.GetData, it only lets you make it a one dimensional array instead of a 2D one. This makes it much more difficult to work with. Is there a specific reason it's like that?


texts: Determine height on Bresenham line algorithm path

texts:
I have path from Bresenham line algorithm, example for A->B vector:

Path is [(0,5), (0,4), (1,4), (1,3), (1,2), (1,1), (2,1), (2,0)]. Considering A height is 10 meters, B height is 5 meters and a tree at position 1,1 is 5,5 meters:

How to know if point B is visible from point A ? My real question is: How to know the A->B vector height when it is "above" specific position, so here 1,1 ?


texts: How to organize objects in a tile-based game

texts:
I'm currently developing a tile-based RPG from scratch using C++ and SFML2.

So far, I got the map rendering and collision detection working just fine and in a clean, maintainable way. The next step is to implement objects on the map with which the player can interact and it feels like this is a bigger problem than it should be.

Here is an example what I want to do: Let's say there is a switch object, that has the property if it is on or off. Additionally there is a door object that has the property if it is open or closed and a list of switches. The controller will now iterate through all objects, if it is a Door, check all the switches assigned to it and if all of them are on, open the door.

My first, naive approach would look like this:

class GameObject
{
   //some common attributes
}

class Switch: GameObject
{
   bool isOn;
};

class Door: GameObject
{
   bool isOpen;
   vector<Switch> switches;
};

The problem is that different objects have different attributes and using inheritance would cause a ton of classes and I had to implement a new class every time I want to introduce a new object. Additionally to the clutter that causes, it would also not be very efficient as the controller had always look up the concrete type of the object it is iterating over and casting it to that type. Constantly having to look up the derived types of a type is also a sign of bad design.

Is there a better way to organize the objects than using classes and inheritance? I looked up the Entity-Component-System Pattern which looks like it's addressing this problem but it feels like an overkill for what I want to do. Also ECS don't fit in with my current architecture and seems in general not very suitable to be used in a tile-based game.

I'd really appreciate any ideas or hints! Thanks a lot in advance!

Edit:

To clarify, here are my issues I have with ECS and tile maps: I currently organized the data of the map like this:

map<Coordinate,Tile> mapData

This is pretty efficient when it comes to collision detection. So with an ECS, I have following options:

I could create a tile entity with coordinates and tiletype as components. That would make collision detection very inefficent. I'll have to iterate over every entity to look up if there is even a tile at the given position.
I could have an entity that holds the whole tile map in a tile map component but that would be a misuse of components as far as I understood the concept.
Using the tile map as an external, non-entity object and inject it to systems that needs it. That's kind of the opposite of what I want to achieve. I want to have a list of dynamic entities to be used on a map and end up building everything around entities, and build exceptions into the architecture.


texts:
Here is the situation.

I have hexagonal board,and a unit on it,with speed or move value 4.Diffrent terrain has a diffrent cost.When i click on the unit,game should show me a move range.

My solution was to check each  hex in range of 4,with A* pathfinding,and if path cost was less than 4 then this hex was in range.Finally game nicely show me range of that unit.

My question is:
  Is there other solution to search for range on hex grids or square grid,because even if i am really proud of what i did in my solution,i think,it is a little to exaggerated?:))

What make me ask this question?I noticed that when unit speed is 4 or 6 or even 8,time to computing range for my computer was really good,but when speed was 10 and more i noticed that i needed to wait few second to compute.Well in real games i rather dont see something like this and my A* pathfinding is rather well optimized,so im thinking that my solution is wrong.

Thanks for any replies.


texts: FOSS games using original assets, is it legal?

texts:
Can I make a game that uses the assets of another game on the users' computer, without legal issues? For example, I make a game that requires the user have game X installed, and I use the assets of game X in my game. The assets of game X would not be distributed with my game.

I realize it will be hard for companies to check, but can you use the assets for other purposes than originally intended (playing the original game)?

As a more concrete example, is playing a game like OpenXcom really legal, when you own the original game?


texts: LibGDX - Box2D: Realistic Light and Layers

texts:
I'm having some problems with my current game. Short description: It's a 2D game where you have to avoid the lights or you lose HP.

My problem is the following one:

Here is the rendering process:

The background is drawn
The Moon image is drawn
The point light is applied
The collision layer and the images attached to it are drawn
Player is drawn
The foreground image (on the top left and bottom middle)

My problem is that the rendering does not look realistic. I need some help on how I could make the light coming from "behind" the collisions and applying it everywhere.

Thanks for your help.


texts: is there any method to simply ignore some files in unity build?

texts:
as im trying to build my new app on unity android specially when i want to use gradle, there is always some conflict with manifest or libraries and .....

for debug and problem exploration i need to ignore some folders to check for those bugs instead of need to move them somewhere else.

i just thought about git branching but it can cause lots of branches and maybe not efficient


texts: Interpolation UNITY taking longer than expected

texts:
I'm trying to do multiplayer interpolations with the lidgren network (UDP) but the interpolation is taking longer than expected and the message queue is getting full. It's been a week and I still can't find the issue.

Here's an approximate code:

    private void Update()
    {
        if (networkUpdates.Count > 0 && CurrentUpdate.Finished)
        {
            var update = networkUpdates.Dequeue();

            CurrentUpdate = NextVesselUpdate;
            NextVesselUpdate = update;

            StartupInterpolation();
        }
    }

    private void StartupInterpolation()
    {
        CurrentVesselUpdate.NextUpdate = NextVesselUpdate;
        StartCoroutine(CurrentVesselUpdate.ApplyUpdate());
    }

    //In the CurrentVesselUpdate class....

    public IEnumerator ApplyUpdate()
    {
        InterpolationDuration = NextUpdate.SentTime - SentTime;
        for (float p = 0; p <= 1; p += (Time.delta / InterpolationDuration))
        {
            ApplyInterpolations(p); //Several lerps here
            yield return null;
            Finished = true;
        }
        ApplyInterpolations(1);//Several lerps here
    }


texts: Application to record sound effects for games

texts:
I'm having kids record sounds using their PCs (a few have Macs as well) for use in the games they create.  The built-in windows 7 sound recorder is surprisingly poor, didn't older versions of windows include a sound recorder that could at least play back the sound you recorded or tell you how long it was?

I tried Audacity, but that is pretty confusing for kids.  They record a sound, don't like it, then want to record again and it merges those 2 sounds instead...  It's also a little confusing trying to simply specify when the sound starts and ends.

Is there some tool game developers use to easily create sound effects from a mic?


texts: Unity Move sprite from point A to point B

texts:
Pretty new to Unity and i'm trying to make a very simple iphone game. , I'd like to know how to move a sprite (2D) move from random point A to random Point B not just that, but i want it to change direction halfway through.

here is my attempt:

public float speed;
public float minForce;
public float maxForce;
public float counter;
private float counter2;

void Start ()
{
    Push ();

}

void Update ()
{
    counter2 -= Time.deltaTime;
    if ( counter2 < 0)
    {
        Push ();
        counter2 = counter;

    }

}

void Push ()
{
    float force = Random.Range(minForce, maxForce);
    float x = Random.Range(-1f, 1f);
    float y = Random.Range(-1f, 1f);

    rigidbody2D.AddForce( force * new Vector2(x, y) * speed);
}

}

I'm not quit satisfied with using force, also tried Vector2.lerp but for some reason it just teleported instead of smoothing. Also i want to make it randomly change position only once.

here is my perp attempt:

 private Vector2 startPoint ;

public float speed ;
public float counter;
private float counter2;

void Start ()
{
    startPoint = transform.position;
}

// Update is called once per frame
void Update ()
{
    counter2 -= Time.deltaTime;
    if ( counter2 < 0)
    {
        RandomPosition ();
        counter2 = counter;

    }

}

void RandomPosition ()
{
    float counter = speed * Time.deltaTime;
    float x = Random.Range(-50f, 50f);
    float y = Random.Range(-100f, 100f);
    Vector2 endPoint = new Vector2(x, y);
    transform.position = Vector2.Lerp(transform.position, endPoint,       Time.deltaTime * speed);
}
}


texts: Cant load model from Content in latest Monogame version

texts:
Using MonoGame 3.4, I'm trying to display a simple textured basketball.

Within the Game1 class, I've created Model mModel. My Initialize function contains all the proper Matrix information. When I run the program, I get an error stating ContentLoadException was unhandled and Could not load basketball02 asset as a non-content file!

protected override void LoadContent()
{
    mModel = Content.Load<Model>("basketball02");
}

I used the MonoGame Pipeline application to build the required xnb files for the Content folder, but for some reason this error keeps popping up and mModel returns null. I've even changed the model's Build Action to Content and Output Directory to Copy if newer like other sites and forums suggested, but still got the same results. (VS2015)


texts:
I have a simple code that will be enabled when I kick, so I disable it right away but even though it is disabled, it works somehow. can it be because of his parent or something else I dont know of?

//this is the script Kick_Test, i dont reach it from anywhere else
private GameObject ball;
private Rigidbody2D rg2d;
public int power = 30;

void Start()
{
    ball = GameObject.FindGameObjectWithTag("Ball");
    rg2d = ball.GetComponent<Rigidbody2D>();
    this.enabled = false;
}

private void OnTriggerEnter2D(Collider2D col)
{
    if(col.tag == "Ball")
    {
        Debug.Log("KİCK");
        Vector2 pos = (transform.position - col.gameObject.transform.position).normalized;
        rg2d.AddForce(-pos * power, ForceMode2D.Impulse);
    }
}


texts: Tile-based 2D collision detection problems

texts:
I'm trying to follow this tutorial http://www.tonypa.pri.ee/tbw/tut05.html to implement real-time collisions in a tile-based world.

I find the center coordinates of my entities thanks to these properties:

public float CenterX
{
    get { return X + Width / 2f; }
    set { X = value - Width / 2f; }
}
public float CenterY
{
    get { return Y + Height / 2f; }
    set { Y = value - Height / 2f; }
}

Then in my update method, in the player class, which is called every frame, I have this code:

public override void Update()
{
    base.Update();

    int downY = (int)Math.Floor((CenterY + Height / 2f - 1) / 16f);
    int upY = (int)Math.Floor((CenterY - Height / 2f) / 16f);
    int leftX =     (int)Math.Floor((CenterX + Speed * NextX - Width / 2f) / 16f);
    int rightX = (int)Math.Floor((CenterX + Speed * NextX + Width / 2f - 1) / 16f);

    bool upleft = Game.CurrentMap[leftX, upY] != 1;
    bool downleft = Game.CurrentMap[leftX, downY] != 1;
    bool upright = Game.CurrentMap[rightX, upY] != 1;
    bool downright = Game.CurrentMap[rightX, downY] != 1;

    if(NextX == 1)
    {
        if (upright && downright)
           CenterX += Speed;
        else
           CenterX = (Game.GetCellX(CenterX) + 1)*16 - Width / 2f;
    }
 }

downY, upY, leftX and rightX should respectively find the lowest Y position, the highest Y position, the leftmost X position and the rightmost X position. I add + Speed * NextX because in the tutorial the getMyCorners function is called with these parameters:

getMyCorners (ob.x+ob.speed*dirx, ob.y, ob);

The GetCellX and GetCellY methods:

public int GetCellX(float mX)
{
    return (int)Math.Floor(mX / SGame.Camera.TileSize);
}
public int GetCellY(float mY)
{
    return (int)Math.Floor(mY / SGame.Camera.TileSize);
}

The problem is that the player "flickers" while hitting a wall, and the corner detection doesn't even work correctly since it can overlap walls that only hit one of the corners. I do not understand what is wrong. In the tutorial the ob.x and ob.y fields should be the same as my CenterX and CenterY properties, and the ob.width and ob.height should be the same as Width / 2f and Height / 2f. However it still doesn't work.

Thanks for your help.


texts: how much memory does Adreno 320 GPU provide?

texts:
I wanted to know how much memory does  Adreno 320 GPU provide ? I am using Nexus 4.

I Googled about it and not able to find any details about it. Can anyone provide the details?


texts:
Here's where I'm at.

Here's where I want to be

Here's how it's drawn

SKShapeNode *fov = [SKShapeNode node];
UIBezierPath *fovPath = [[UIBezierPath alloc] init];
[fovPath moveToPoint:CGPointMake(0, 0)];
[fovPath addLineToPoint:CGPointMake(fovOpposite *-1, fovDistance)];
[fovPath addLineToPoint:CGPointMake(fovOpposite, fovDistance)];
[fovPath addLineToPoint:CGPointMake(0, 0)];
fov.path = fovPath.CGPath;
fov.lineWidth = 1.0;
fov.strokeColor = [UIColor clearColor];
fov.antialiased = NO;
fov.fillColor = [UIColor greenColor];
fov.alpha = 0.2;
fov.name = @"playerFOV";
[_playerImage addChild:fov];

Now, I'm not expect the answer of "use this code" I'm hoping someone can point me down a logical path of determining how to emit the field of vision, and if it encounters an obstacle, it stops drawing.


texts: Calculate Distance Using Lifetime, Speed, and Time Between Ticks

texts:
I am trying to draw a line from the player to where he is facing, with the line being the distance his rockets will travel. I have ShipMissile.Speed, which is the number of pixels to move per tick, LastTick, the number of milliseconds between each call to Update(), and ShipMissile.Lifetime, which is the number of 10 ms ticks that the missile should be alive for. My current code is as follows:

Distance = (int)((ShipMissile.Speed * ((ShipMissile.Lifetime * 10) / LastTick)) * scale);

LastTick is generally 16.6667 (I have never seen it vary from this value during testing), and for this particular missile type Lifetime = 200, which is 2000 ms, Speed = 7, and scale = 1 ('native' game resolution).

The missile moves by using its rotation to generate a normalized vector, then multiplies by Speed and scale each game tick.

EDIT: Like this:

Missile.Position += direction * speed * scale;

I am finding that the line is too short, and am wondering where the flaw in my code is (and please do not mention that I shouldn't be so dependent on frame rate or not be updating Lifetime outside of Update)? Is it even possible with my current (non optimal) setup? Thanks!

EDIT: I know this is kind of late, but here is a picture of what I mean (ignore the other stuff like the enemy and the score, etc):


texts: Algorithm for sensing mouse movements like a wiimote

texts:
I want to make a driving game where you can do tricks with your mouse when you hold down LMB. Ex. if you move it up in a straight line really fast (your cursor goes from the bottom to the top of the screen in, say, 0.1s),  your bike will do a flip. If you do a quick circular movement, your bike will spin. Essentially, drawing a shape onto the screen = performing a move.
How would this be sensed? Currently, I can only think of having shapes defined by coordinates relative to some starting position (it would be some function taking in your mouse down coords), and within a certain time frame, every update loop will check to see if the current mouse coordinate pair is between the current preset one and the next preset one (and within a margin of error). To know which shape to use, you'd loop through the shape list, see whether or not the mouse coord is invalid for the current shape, and knock it off the possibilities if true.
Example circle path:

X = Coordinate
Red arrows = Expected mouse movement path
Green = Margin of Error

Problems I can see with this algorithm right now:

If I have a lot of moves, then there are a lot of shapes to loop through every frame before the deduction process kicks in
It's not an optimal solution for doing consecutive moves in a short timespan, because the player would have to release LMB before pressing it down again for the system to sense that a new shape is starting
Tiny circles vs big circles, how wide the margin of error would need to be to allow for both, and how that would affect calculations (clashing with other shapes that have similar valid spaces)
What if you draw circles like flattened, diagonally skewed ovals, even when you're not trying to do it fast? It is indeed a circular motion, but maybe diagonally skewed ovals are for another move. Is it okay to just shun your artistic ability?
How much time will it take before the system recognizes that you're doing a specific move? Must a full circle be completed before any bike spinning occurs?

What would be a better algorithm?


texts: Why is my collision detection not accurate?

texts:
After trying and trying, I still cannot understand why the leg of character exceeds the wall but no clipping issue when I hit the wall from below. How should I fix it to make him stand still on the wall?

From collideWithBox() function below, it shows that playerDest.Y = boxDest.Y - boxDest.height; will get the position the character should standstill on the wall. Theoretically, the clipping effect won't be happen as the character hit the box from below works with the equation playerDest.Y = boxDest.Y + boxDest.height;.

void collideWithBox()
{
    if ( spriteCollide(playerDest, boxDest) && keyArr[VK_UP])
        //playerDest.Y += 50;
        playerDest.Y = boxDest.Y + boxDest.height;
    else if ( spriteCollide(playerDest, boxDest) && !keyArr[VK_UP])
        playerDest.Y = boxDest.Y - boxDest.height;
}

void initPlayer()
{
    //  Create texture.
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "player.png", 169, 44,
        D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
        D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
        NULL, NULL, &player);

    playerRect.left = playerRect.top = 0;
    playerRect.right = 29;
    playerRect.bottom = 36;

    playerDest.X  = 0;
    playerDest.Y  = 564;

    playerDest.length = playerRect.right - playerRect.left;
    playerDest.height = playerRect.bottom - playerRect.top;
}

void initBox()
{
    hr = D3DXCreateTextureFromFileEx(d3dDevice, "brock.png", 330, 132,
        D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
        D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255),
        NULL, NULL, &box);

    boxRect.left = 33;
    boxRect.top = 0;
    boxRect.right = 63;
    boxRect.bottom = 30;

    boxDest.X = boxDest.Y = 300;

    boxDest.length = boxRect.right - boxRect.left;
    boxDest.height = boxRect.bottom - boxRect.top;
}

bool spriteCollide(Entity player, Entity target)
{
    float left1, left2;
    float right1, right2;
    float top1, top2;
    float bottom1, bottom2;

    left1 = player.X;
    left2 = target.X;
    right1 = player.X + player.length;
    right2 = target.X + target.length;

    top1 = player.Y;
    top2 = target.Y;

    bottom1 = player.Y + player.height;
    bottom2 = target.Y + target.height;

    if (bottom1 < top2) return false;
    if (top1 > bottom2) return false;

    if (right1 < left2) return false;
    if (left1 > right2) return false;

    return true;
}


texts: Unity - Setting Script Execution Order inside a package

texts:
When working inside of a Unity project, to set up the execution order for all the scripts is quite easy. It can be done under "Project settings". But when working developing a package, this option is not available, since we are not developing actively a Unity project.

But at the same time, I wish that every project that imports my package executes its scripts in the right order, without the user needing to set it up manually for every project.

How can this be achieved?


texts: Trying to convert Unreal shader graph to Unity, what nodes are a close equivalent in the Unity shader graph?

texts:
I am trying to convert an Unreal shader graph to a Unity Shader Graph.

https://api.unrealengine.com/udk/Three/VolumetricLightbeamTutorial.html

I am struggling with understanding which nodes to use in the Unity Shader Graph while trying to replicate it.

I managed to get something looking Ok using the fresnel node, but if you enter inside the geometry, you lose the effect.  I found the above article which is perfect for what I need to do.

Here is the first node setup:

I tried to follow along but a lot of the nodes I don't understand what the equivalent would be in the Unity shader graph.

Combine looks to be the equivalent of the Append node I think.
Mask node I am not sure about as there are 3 mask nodes in Unity shader graph.

Edit:

Spent most of the weekend trying to learn which nodes to use.  Still not sure on what the "Reflection Vector" should be.  I think it's something to do with the camera.

Here is the graph currently.


texts: Android OpenGLES, getting number of fragments passed depth test/Occlusion Query?

texts:
Afeter reading many blogs and searching on Internet, I did not get any sloution for getting number of fragments/pixels which are occludded or not occludded of the object on OpenGL ES3.0 Android version.
GL_SAMPLES_PASSED is not present on OpenGL ES3.0.
Is there any way to get these occluded or non occluded fragments on Android OpenGl ES3.0?


texts:
I am using latest unity engine and I am having a scripting issue.

I create a prefab , added a few scripts to it and I am trying to instantiate a few of those objects like this :

        GameObject go = Instantiate(Prefab) as GameObject;
        var co = go.GetComponent<MyScriptA>();

Issue here is co is always null, this means that MyScriptA is no on the go instance.
Accessing the prefab.GetComponent also returns null, but the prefab has the scripts in the editor and its assigned also in the editor to the Prefab variable (drag dropping). So I am not sure what might be wrong.
For example if I Debug.Log(prefab) its not null.

So what am I doing wrong here?


texts: Save data in scene without transferring game object in Unity

texts:
My game requires the user to continuously come back to a particular scene

DontDestroyOnLoad transfers the gameobject from one scene to another (without destroying it).

Is there a way to save the data in a scene without transferring the game object, but when the user comes back to the 'particular' scene, it continues from there.

for e.g

inputgiven = false

if(input.anyKeyDown){

inputgiven = true;
Application.LoadLevel("Scene2");
}

So when the user comes back to this scene input.given = true.

I am sorry if the question or some aspects of the question are unclear. This was really hard to explain.
(please just leave a comment if it is unclear)


texts: Image with FadeIn effect blinks when added to scene

texts:
I am trying to add an image to the scene, but it should just be added to the scene invisible, FadeIn and then be deleted when the effect finishes.

My problem is that the images blink once when they are added to the scene, then they do the intended effect. My best guess is that when they are added they show on the scene for a split second before starting the animation. I though of making them invisible for a split second before activating them, but I am not sure how to code it.

 const bool Sunbeams::add()
{
const CCSize kSceenSize = CCDirector::sharedDirector()->getWinSize();

const int nRayType = random( m_kRays.size());

const CCPoint kPosition( random( static_cast < int >( kSceenSize.width)),
                         0.0f);

const float fDuration = random( m_fDurationVariance) + m_fDurationMin;

CCSprite* pkLightBeam = CCSprite::spriteWithTexture( m_kRays[nRayType]);

if ( !pkLightBeam)
{
    msg::debug( "Sunbeams::add",
                "Failed to create sprite from ray '%d'!\n",
                m_kRays[nRayType]);

    return false;
}

pkLightBeam->setAnchorPoint( CCPointZero);

pkLightBeam->setPosition( kPosition);

m_kActiveBeams.push_back( pkLightBeam);

CCDirector::sharedDirector()->getRunningScene()->addChild( pkLightBeam);

CCActionInterval* pkAction = CCFadeIn::actionWithDuration( fDuration);

CCActionInterval* pkActionBack = pkAction->reverse();

pkLightBeam->runAction( CCSequence::actions( pkAction,
                                             pkActionBack,
                                             0));

return true;
}


texts: how to create a Quaternion from an Orientation Vector in xna

texts:
I have a Vector3 represents an Orientation in 3D , how to convert it to the corresponding Quaternion ?
Is there any quick way ?

EDIT :
I want to add an angular velocity vector to the Orientation Quaternion of the body


texts: Color bleed on voxel edges when using anti-aliasing

texts:
My Minecraft-like game uses a texture containing four block IDs in each pixel (RGBA). These IDs are used in the shader to determine what color each whole block should be.

I'm having an issue with anti-aliasing because WebGL is assuming that vertices are flat with the texture, which isn't the case. As you can see from this image, green pixels are visible on the edges (as the next pixel on the texture is green):

With anti-aliasing:

Without anti-aliasing:

Here's my code:

gl.activeTexture(gl.TEXTURE1);

var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, float32Array);

gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);

gl.bindTexture(gl.TEXTURE_2D, texture);

var z = gl.getUniformLocation(material.program, "uSampler");
gl.uniform1i(z, 1);

Does anyone know how I would solve this? From what I've read, is this something that overdrawing would fix? Thanks.


texts: How to swap between two player objects in Unity?

texts:
I have two object for the player. Whenever I press space I'd like to swap between them and also I would like to change the first player main camera to the second player camera and equally for the minimaps. It's the same as swaping a between characters in a LEGO game.
When I try this in the "Game" window, the camera should focus on the first player, but for some reason it doesn't. Neither does the first object move on WASD or on arrow keys presses. The second object is dead. The cameras are basically a dirty trick and I really need only two. Both players have the same PlayerController script attached.

PlayerController.cs UPDATED 10.01.2018 20:45 CET - Basically what I wanted to have

using UnityEngine;

public class PlayerController : MonoBehaviour {

public float speed;

public GameObject playerAtDockCamera;
public Camera playerAtDock;

public GameObject playerAtSeaCamera;
public Camera playerAtSea;

public Rigidbody p1; //player object one
public Rigidbody p2; //player object two

private bool atSea = false;
private Rigidbody rb;
private Vector3 cameraposition;

void Start ()
{
    rb = p1;
}

private void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        atSea = !atSea;
    }
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");

    float moveVertical = Input.GetAxis("Vertical");

    if (!atSea)
    {
        if (rb == p2)
        {
            rb.velocity = Vector3.zero;
            rb = p1;
        }
        EnableDock();
        rb.AddForce(new Vector3(moveHorizontal, 0.0f, moveVertical) * speed);
       }
       else
        {
        if(rb==p1)
        {
            rb.velocity = Vector3.zero;
            rb = p2;
        }
        EnableSea();
        rb.AddForce(new Vector3(0.0f, 0.0f, moveVertical) * speed);

 }
}
void EnableSea()
{
  playerAtDock.enabled = false;
  playerAtSeaCamera.SetActive(true);
  playerAtSea.enabled = true;

}
void EnableDock()
{
    playerAtDock.enabled = true;
    playerAtSeaCamera.SetActive(false);
    playerAtSea.enabled = false;

}
}


texts:
When I was a kid, everything had a speech synthesizer in it, more or less. A couple years back I started to wonder where the technology is going after all these years, and after some research found that it's going nowhere. Storage has increased, making concatenative synthesis more life-like, but little else has improved.

Text to speech seems to be the primary research field. Most books I've found of the subject of speech synthesis skim on the actual voice generation and then spend hundreds of pages on text to speech.

I'm not interested in text to speech as such, but more on the voice generation. Yet, I haven't found a single book with good, practical explanation of this. Concatenative synthesis is simple to grasp, but formant is the one I'd like more information about. (The third method, physical modelling, would be a plus, but not all that interesting).

What makes this game specific is that I'd love to make a tool that lets low budget/downloadable games have speech, without having to go out to get actual voice actors and having to store hundreds of megs of oggs with the game. Since the author is in complete control of the voice editing before release, text to speech is less important; what's more important is the voice synthesis.

So, anyone know any good books about this?


texts: How do I rotate a gameobject towards a point in world space?

texts:
I wanted to create a very simply turret.
This turret should aim at the point on the screen where the mouse pointer is currently located.
I have added a cube to serve as a very simple turret in my scene.
To visualize its aiming direction, I'm drawing a ray from it.

To rotate the "turret" to the mouse pointer position, I have created a script and added it to the "turret" gameobject:
void Update()
{
    var mousePos = Input.mousePosition;
    mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
    var aim = Camera.main.ScreenToWorldPoint(mousePos);

    transform.LookAt(aim);

    RaycastHit hit;

    int layerMask = 1 << 8;
    layerMask = ~layerMask;

    Color color;
    if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
    {
        color = Color.green;

    }
    else
    {
        color = Color.red;
    }

    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 10000, color);
}

However, there must be something wrong in my code.
In this screenshot, I have added a red arrow that points to the position of the mouse pointer:

The mouse pointer is over that orange tool. However, the turret is rotated towards the floor while it should be rotated upwards to the orange tool.
I do believe that my turret is well positioned (the blue arrow points forward):

How do I change my code so that it aims correctly, and what is my mistake?
I guess the problem is in these 2 lines, but I don't see what's wrong about it:
    mousePos += Camera.main.transform.forward * 10f; // Make sure to add some "depth" to the screen point
    var aim = Camera.main.ScreenToWorldPoint(mousePos);

Thank you.
Edit:
I finally understand what Kevin wanted to tell me.
I made a thinking mistake, and really need the Raycast to determine where my Worldspace point actually is.
Here is why:

Even though the Y screen coordinate of the mouse position is just a few pixels different in each game window on the right side, the worldspace point is totally different (as can be seen in the scene view window on the left side).
I thought in 2D space, while I should have thought in 3D space.


texts: Resize font when screen resizes desktop Libgdx

texts:
I create my font using the following code:

public BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp)
{
    FreeTypeFontParameter f = new FreeTypeFontParameter();
    f.size = (int)(dp * Gdx.graphics.getDensity());
    f.color = Color.BLACK;
    f.minFilter = Texture.TextureFilter.Nearest;
    f.magFilter = Texture.TextureFilter.MipMapLinearNearest;
    ftfg.scaleForPixelHeight((int)(dp * Gdx.graphics.getDensity()));
    return ftfg.generateFont(f);
}

myFont = createFont(new FreeTypeFontGenerator(Gdx.files.internal("Fonts/Roboto-Black.ttf")), 16);

I have some labels to which I set the font using:

Label myLabel= new Label("Text", uiSkin);
        myLabel.setWrap(true);
        myLabel.getStyle().font = myFont;

How I create the stage:

Stage collectionStage = new Stage(new StretchViewport(Gdx.graphics.getWidth(), Gdx.graphics.getWidth()));

I also tried with no viewport or with other viewports.

In my resize method:

public void resize(int width, int height) {
    Viewport viewport = collectionStage.getViewport();
    viewport.update(width, height, false);
    viewport.apply();
}

The problem is that when I resize the window on Desktop the font gets distorted. Do I have to create another font in the resize method, and then for each label that I have, reassign the new font? Or should I do something else?


texts: Can I make the project files/source code of my comerical Unity game avalible as a DLC or with the game?

texts: Is it legal and/or a good idea to let the players download the source code/project files of a comerical Unity game with the game or as a DLC?


texts: How can I create a random "world" in a tile engine?

texts:
I am designing a game that is working on a classic tile engine, but whose world is generated randomly. Are there existing games or algorithms that do this?
The procedural generation algorithms I have found are never using a tile system...
What would be the best way to generate a whole "world" using a tile system? I am not talking about mazes of blocks, but an overall "world map"
thanks


texts:
I'm trying to write a simple collision system, which will probably be primarily used for 2D platformers, and I've been planning out an AABB system for a few weeks now, which will work seamlessly with my grid data structure optimization. I picked AABB because I want a simple system, but I also want it to be perfect.

Now, I've been hearing a lot lately about a different method to handle collision, using sensors, which are placed in the important parts of the entity. I understand it's a good way to handle slopes, better than AABB collision.

The thing is, I can't find a basic explanation of how it works, let alone a comparison of it and the AABB method. If someone could explain it to me, or point me to a good tutorial, I'd very much appreciate it, and also a comparison of the advantages and disadvantages of the two techniques would be nice.


texts:
I just started OpenGL (PyopenGl) & Pyglet 3 weeks ago, and decided to read the Red Book. So sorry if my question shows my lack of comprehension...

My question is: Is it possible to display/write text using  text.Label().draw  in a FBO ?

What I want to do is use text.Label().draw to generate a texture and use that texture when I need it. But so far I haven't been able to do it. (lack of comprehension/experience?) I know that text in OpenGl is usually done by Bitmap Fonts, Outline Fonts or Texture Mapped Text, but I was wondering if the method I am thinking of could be a sortcut.

So sorry again if this question is stupid/obvious, but I'm still learning and did spend a lot of time looking/searching for an answer.

Thanks guys.


texts:
How to do screen record in unity? I want to record my screen(gameplay) during my running game. That should be play/stop , replay , save that recording on locally from device, open/load from my device (which is already we recorded).

In my game one camera which can capture native camera, and one 3d model.

I wish to record that both and use my functionality whenever i want.

Thank you in advance.


texts: How to implement camera pan like in Maya?

texts:
I am trying to implement camera pan like the one in Maya. I've got it almost working.

The problem is that the mouse cursor is moving faster than the 3d mesh (in fact I am moving the camera but I said mesh, because it is more intuitive), while in Maya the distance between the mouse position and the mesh stays always the same.

This is what my code looks like :

glm::vec3 dist = cameraPos-modelPos;
float len=glm::length(dist);

float clipX = startX*2.0 / width - 1.0;
float clipY = 1.0 - startY*2.0 / height;

float clipEndX = lastX*2.0 / width - 1.0;
float clipEndY = 1.0 - lastY*2.0 / height;

// convert begin and end mouse positions into world space
glm::mat4 inverseMVP = glm::inverse(projection*view*modelMatrix);
glm::vec4 outVector = inverseMVP*glm::vec4(clipX, clipY, 0.0, 1.0);
glm::vec3 worldPos(outVector.x/outVector.w, outVector.y/outVector.w, outVector.z/outVector.w);

glm::vec4 outEndVec = inverseMVP*glm::vec4(clipEndX, clipEndY, 0.0, 1.0);
glm::vec3 worldPos2(outEndVec.x/outEndVec.w, outEndVec.y/outEndVec.w, outEndVec.z/outEndVec.w);

glm::vec3 dir = worldPos2 - worldPos;

glm::vec3 offset=glm::length(dir)*glm::normalize(dir)*angleFovRatio*len/2.f;
cameraPos-=offset;
cameraTarget-=offset;

Where angleFovRatio = std::tan(cameraFov*0.5f)
I am using glm::lookAt(cameraPos, cameraTarget, cameraUp); for my view matrix

I will add picture of what my problem is:

As you can see, when I drag to the right, the red dots are my begin and end mouse positions. But the teapot is on the blue dot, which is not what I want.
It must be centered on the second red dot (mouse end position, just like in maya).


texts: AntTweakBar doesn't register SFML mouse events

texts:
I'm trying to add GUI for easier level editing in our game engine. We're using SFML for all the basic stuff (window management, input events etc). I've chosen AntTweakBar because it is a well known library with a few examples around. I was following the tutorial at AntTweakBar's website

I was able to draw a simple bar with those example codes. However, mouse events received by SFML are not registered by AntTweakBar's TwEventSDL() function. Here is an example code for Input:

sf::Event event;
while (_pWindow->pollEvent(event))
{
    // Check if the event should be handled by AntTweakBar
    int handled = TwEventSFML(&event, 2, 3); // for SFML version 2.3
    if (!handled){
        switch (event.type)
        {
        case sf::Event::MouseButtonPressed: // To check whether SFML received mouse button events properly
            if (event.mouseButton.button == sf::Mouse::Button::Left){
                std::cout << "Left button pressed" << std::endl;
                std::cout << "x: " << event.mouseButton.x << std::endl;
                std::cout << "y: " << event.mouseButton.y << std::endl;
            }
        }
    }
    else{ //To check whether TwEventSFML received events
        std::cout << "FINALLY!" << std::endl;
    }

When I press buttons, I can see "FINALLY!" showing up. I can also see that my mouse clicks are received by SFML. However, when I click on an AntTweakBar element (be it a button or help section) it doesn't register it. (Also, I can't see "FINALLY!" when I use the mouse).

Any help or ideas will be appreciated.


texts: Mapping of positions on images in different frames

texts:
I am looking for a possibility to map different positions on a 2D Image which has different frames.
Let's say I have an image, consisting of three frames, which shows a spaceship.
The first frame shows the spaceship how it is tilted a little bit (say 20 to 30 degree) to the left side.
The second frame shows the spaceship just from the top.
The last frame shows the spaceship tilted a little bit to the right (the same amount as in frame 1).
Now I want to know, where for example the part which is in the middle of the second frame, is in the first and third frame.
The following painting should show what I mean (sorry, I am a bad artist):

The red arrows show example positions which I want to match.

The background is the following: I want to have the possibility to take away parts of the image while playing.
The problem is: I want that the parts which were taken away, are taken away on every frame at the right position.

I fail to imagine how to approach this problem as I cannot think of a possible solution.
Is there a possibility to achieve this goal or is it just impossible?


texts: How to calculate turret position after rotation

texts:
I'm trying to make a tank character for my game but I couldn't do the math of firing bullets from turret instead of center of the tank.

I tried some Stack Overflow solutions but I couldn't understand them correctly or they weren't related to my issue.

this.angle = (rotation in radians) + Math.PI / 2
var x = -40 * Math.sin(this.angle) - -40 * Math.cos(this.angle);
var y = -40 * Math.cos(this.angle) + -40 * Math.sin(this.angle);

turretX = turretX - x;
turretY = turretY - y;

Now, as you can imagine, the position is always 40px wrong. That's expected since I try to change values of both x and y regardless of whether they're already correct or not.

How can I get the correct x, y?


texts: How to deal with crackers who are also trolls?

texts:
Assuming the following:

the game will be cracked at some pont no matter what
players are pushing to the limits
trolls exist

What happens when these 3 combines?

Regulating a troll can be handled if the device / game is not cracked, i.e. kick out, ban etc.

But how to handle someone who comes online with different identities and ruins others fun?

Do you check patterns? (same IP, being cooperative instead of competitive?)
Should this be crowd sourced like in wikipedia and add rights to trusted users?

We are having these issues, even though our game has only a small community.

Is the game free, or is a subscription / purchase required? Is the online element peer to peer or does it go through a server under your control? – Adam 5 mins ago

Answers to Adam's comment:

iOS game. Free version is available without multiplayer
Traffic goes through a server and is under our control


texts:
I have been trying to implement a simple form of lighting in my 2D game. In the screenshot, I don't think it looks very good, kind of just plastered over the top of the map. How would the wall effect how the lighting is displayed?

Just looking for tips on how to make my lighting look a bit better. Right now I gave each tile a light value and I change that depending on if there is a light source near by. I don't take in account if there are any objects near by.

Screenshot:


texts: Handle game flow in turn-based game on server or client side?

texts: Im building a turn-based game using websockets and nodejs. At the end of each turn I want to show some scores before starting the next turn. Should that be controlled by the server using a timer? Or should the client start a timer and tell the server when it's ready for next turn? Just to keep the load of the server. What is the pros/cons?


texts: How do I use Objective-C libraries in Cocos2d-x?

texts:
We've created several libraries in Objective-C in the past, and now we're moving to the Cocos2d-x game engine. We can't figure out how to reference and use those libraries (we've also tried compiling them as Objective-C++ libraries).

How can we reference and use those libraries in Cocos2d-x?


texts:
First time writing shaders, and having a bit of an issue getting per-pixel lighting to work.  The problem is pretty simple, but I'm afraid am doing something wrong here.

Vertex Shader:

#version 150

uniform mat4 proj;      // ortho projection matrix
uniform mat4 world;     // world transformation (usually only rotation)

in vec2 pos;            // position for this vertex

out vec2 ex_pos;        // pass position to frag shader

void main()
{
    gl_Position = proj * world * vec4(pos, 0.0, 1.0);
    ex_pos = pos;
}

Fragment Shader:

#version 150

uniform vec2  light_pos;        // light position
uniform vec3  light_color;      // light color
uniform vec3  intensity;        // intensity value to apply to the light
uniform float attenuation_c;    // constant attenuation
uniform float attenuation_l;    // linear attenuation
uniform float attenuation_q;    // quadratic attenuation

in vec2 ex_pos;     // interpolated position

out vec4 frag;      // final fragment color value

void main()
{
    // compute the current distance from light
    float d = distance(light_pos, ex_pos);

    // compute attenuation for this point
    vec3 frag_intensity = intensity / (attenuation_c + attenuation_l*d + attenuation_q*pow(d,2) );

    // blend mode is additive
    frag = vec4(frag_intensity * light_color, 1.0);
}

So, this seems pretty straightforward, but I am getting a hopelessly dark polygon (i.e., the additive fragment color always ends up 0,0,0).  I have tested that simply setting d to any positive value causes the entire light polygon area to be uniformly lit, so I'm thinking that my distance computation is just wrong, but I'm not sure how it could be.  I did have this working a bit earlier by doing vertex lighting instead of fragment, so I'm pretty sure my uniforms are being set correctly.

Is it the interpolated position that is causing a problem?

Thanks for any help.


texts:
I have three points, A, B and C (stored as Vector2 in Unity).  I am trying to find the angle at point B if there were a line AB and and a line BC.  I know, this should be a simple google search, and I have found several methods but for some reason, they ALL return totally unexpected results with my data set!

I checked to make sure that the three points I pass to compute the angles are indeed the correct (x,y) coordinates, and that same data is used elsewhere in my code without any problems.

Considering that all functions return strange results, it must be that I am not understanding something here...

here is one formula:

Vector2 A = //some vector2.normalized
Vector2 B = //some vector2.normalized
Vector2 C = //some vector2.normalized
float Angle = Mathf.Atan2(B.y - A.y, B.x - A.x) - Mathf.Atan2(B.y - C.y, B.x - C.x);

Here's another that I tried where p0,p1,and p2 and just vector2's:

function findAngle(p0, p1, p2) {
        var a = Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2),
            b = Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2),
            c = Math.pow(p2.x - p0.x, 2) + Math.pow(p2.y - p0.y, 2);
        return Math.acos((a + b - c) / Math.sqrt(4 * a * b));
    }

The data is a List of Vector2 control points for creating Bezier curves. I want to calculate the angle between index 0,1,2 then 2,3,4 then 4,5,6 etc. with the middle index as the angle needed.

I understand that both formulas return radians, but converting to degrees returns sometimes 180 for all points even though the points are all different and the angles vary greatly, sometimes 0 (if I switch the points around), and in the case of the atan2 function above, it gives numbers that "look" like angles, but plotting the points, one can see that the angles do not correspond to the visual plots...  I must be doing something very dumb here and I'm not great with math so any hand-holding is much appreciated.

Here's an image of the output:


texts:
Recently I asked a question, what is the fastest way to render 2D lines using DirectX, and one of the answers mentioned this paper on Fast Prefiltered Lines which uses Pixel Shaders to accomplish wireframe drawing. This paper draws quads per line segment then uses a pixel shader to draw a line by computing distance from the pixel to the line down the centre of the quad before filling with line-color or transparent.

So, I'm wondering how can this be done? I wasn't aware the pixel shader can get knowledge of the input geometry (e.g. the quad) that creates it. Is the following possible? Ideally in DirectX9 but DX10 or OpenGL solutions also appreciated!

EDIT

Turns out I don't draw the quad like that, but like this. So the question is: How can I get information about x1y1 x2y2 into the pixel shader so I can compute distance to line edge & get a nice antialiased line segment?


texts: Interacting with scene from controller/app delegate cocos2d

texts:
I'm attempting to make my first cocos2d (for iphone) multiplayer game and having difficulty understanding how to interact with a scene once it is running.

The game is a simple turn-based one and so I have a GameController class which co-ordinates the rounds. I also have a GameScene class which is the actual scene that is displayed during a round of the game. The basic interaction I need is for the GameController to be able to pass messages to the GameScene class.. such as StartRound/StopRound etc.

The thing that complicates this is that I am loading the GameScene with a LoadingScene class which simply initialises the scene and replaces the current scene with this one, so there is no reference from GameController to GameScene, so passing messages is quite tricky.

Does anyone have any ways to get around this, ideally I would still like to use a Loading class as it smooths out the memory hit when replacing scenes.


texts: What direction does directional audio come from for a 2D view?

texts:
In a 3D game, it makes sense that stereo balance is based on the angle between your camera direction and the directionto the audio source.

Is 2D audio just "fudge the left-right balance until it sounds good"? Are there games where the audio balance was still character-oriented rather than view oriented (so a character facing south causes stereo balance to be backwards)?

I'd be interested in answers supported by examples where a notable game was played by blind players using audio cues. The only one that comes to mind is Brood War


texts:
I have a VBO storing some data in my game. The thing is, the data can change at a rate of about a second. The data is not fixed size, meaning that some objects will sometimes be visible, sometimes invisible and could even have a different polygon count. I'm trying to figure out how I could do that efficiently using VBOs. In immediate mode, I would simply not call the render method of the single objet, and it would simply not appear! And if I needed more polygons, I would just... call glVertex2f more often! I understand why using immediate mode is really bad in performance, but I really can't think of any good way to "build" the VBO.

I thought about using a list, append the vertices to the list and then create the vbo, but this would have, I think, three drawbacks. More CPU intensive, requires more memory copying, and would require me to recreate (I could work this out) the VBO every time, since I don't know the size before building the lists!

Is there a common way of building a VBO for many small objects without using a list?

Some pseudo code:

void GlobalRender()
{
    foreach (chunk in chunks)
    {
        if (chunk.RequiresUpdate)
        {
            chunk.UpdateVBO(); //In there, that's where I don't know how large I'll need my VBO to be.
        }

        chunk.Render();
    }
}

void UpdateVBO() //The code called above
{
    foreach (node in nodes)
    {
        if (node.Visible)
        {
        //Emit vertices from here!
        }
        else
        {
            //There's nothing here really, just pointing out that there could be no vertices for a single node
        }
    }
}


texts:
I am generating camera frustum mesh through code, it is working fine. Now I am searching a solution (shader based or else) to restrict
the camera frustum mesh if it intersect with any object. Like you can see in the image my frustum is passing through the plane which is not correct.
How can I control it, I search and apply different kind of shader but nothing worked.


texts:
I made a new class that implements Screen, what I've seen from other people's code is that they create a constructor that takes a parameter of Game game. I did not created a constructor, I think that's the reason why I get the error

  public class MainMenu implements Screen{
     public MainMenu(Game game){ //I dont know what are these for
            this.game = game;    //<--
        }

 public void show() {
        btnAtlas=new TextureAtlas(Gdx.files.internal("bitters.atlas"));
        skin=new Skin();
        skin.addRegions(btnAtlas);
        stage=new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true);// I get the error here when initializing the Stage
    }
 }

the error is "Cannon resolve constructor 'Stage(int,int,boolean)'"


texts:
I'm making a game like Doodlejump but don't know how to make the physics scale on multiple resolutions. I also can't find anything related to this on Google. Right now I'm scaling the game using letterboxing and tested scaling the jump height with this code:

gravity = graphics.getHeight() * 0.001f;
jumpVel = graphics.getHeight() * -0.04f;

...

velY += gravity;
y += velY;

But if I test this on my smartphone or emulator with different resolutions, I always get a slightly different jump height. I know that Farseer is resolution independent. How can I replicate this in my game?

Thanks in advance.


texts:
Hi guys I am really new in OpenGL-ES and I am developing a simple android application with NDK, and I just want to ask why the image is not fit after I set the width and height of it.

this is my width and height

const int FIXED_WIDTH = 320;
const int FIXED_HEIGHT = 568;

and this is how I set my Matrix

glViewport(0, 0, width, height);

// Create a new perspective projection matrix. The height will stay the same
// while the width will vary as per aspect ratio.
float left = FIXED_WIDTH;
float right = 0.0f;
float bottom = FIXED_HEIGHT;
float top = 0.0f;
float near = 1.0f;
float far = 50.0f;

mProjectionMatrix = Matrix::newFrustum(left, right, bottom, top, near, far);

// Position the eye in front of the origin.
float eyeX = 0.0f;
float eyeY = 0.0f;
float eyeZ = 1.0f;

// We are looking at the origin
float centerX = 0.0f;
float centerY = 0.0f;
float centerZ = 0.0f;

// Set our up vector.
float upX = 0.0f;
float upY = 1.0f;
float upZ = 0.0f;

// Set the view matrix.
mViewMatrix = Matrix::newLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);

// model * view * projection
mMVPMatrix->multiply(*mProjectionMatrix, *mViewMatrix);

After setting the Matrix I thought that my point 0.0 will start at the top right corner of the device (This is my understanding of matrix). as you shown in the image.

and this is how I setup my texture

TextureGenerator* textureGenerator = new TextureGenerator();
textureGenerator->setSize(320.0f, 568.0f); // width and height
textureGenerator->setTranslate(0.0f, 0.0f); // X and Y
textureGenerator->setTextureId(GLUtils::loadTexture("bg.jpg"));
mTextureCollection.push_back(textureGenerator);

then after I add some texture this is the result.

This is the actual picture, size 320x568.

as you can see to the result of my doing, I don't know if my point 0.0 is starting at the center. Please someone help and explain to me why the texture is not fit, and if my matrix is correctly set or not. Thank you.


texts: How much mathematics is involved in video game development?

texts:
I'm average at maths. Maybe a tad below average. If I was going into a normal career I'd be fine. But I want to create video games. Is a career in video game development still on the cards for me?

I want to be a creative director, but I don't just want to write screenplays, create 3D models and draw concept art (areas I excel at.). I want to actually touch the code. I've been learning web development now for 8 months, and I understand pretty in depth concepts such as serverside fragment caching, and it would damn depressing to throw all those skills away and just hire some programmers when I move into video games. I want to develop alongside them. Is developing video games (with a team) similar to web development, in that it's all OOP and logic but with relatively little arithmetic? I'm not on about creating a 3D engine, I'm sure that's filled with physics and theorems of momentum, I'm on about simply using a ready made 3D engine.

Do you need to be a substantially better at maths than most to develop video games?


texts: Lamba expressions: The => Operator. Any plain English help to understand this please?

texts:
I've been adding Google Play support into my game. For the most part I'm getting on swimmingly, but I'm having a hell of a time understanding exactly how the submission calls to submit score and achievements work.

It's the => operator and surrounding method that confuse me, such as this one that I have in my code. It all works, I just don't know how. I've read up a bit and I think these are called Lambda expressions.

But I want to know why it is this way, and why it isn't made so we can just use the standard typical bool instead of making this strange way to send the result of whether or not our player is logged in.

Hope that makes sense. Here's the code in question:

Social.localUser.Authenticate((bool success) => {
        if (success)
            {
                Debug.Log("score authenticed successfully");
            }
            else
            {
                Debug.Log("score not authenticed, check user is signed in");
            }
     });
    Social.ReportScore(score, GPGSIds.leaderboard_pinball_wizards, (bool success) => {});

Particularly, the bottom line really has me stuck.


texts: Limiting the speed of a dragged sprite in Cocos2dx

texts:
I am trying to drag a row of sprites using ccTouchesMoved. By that I mean that there is a row of sprites (they are colored squares) lined up next to each other and if I grab one with a touch the rest follow it. If a sprite moves off screen I want to append it to the rest of the sprites in formation. However, if the sprite formation moves too fast it creates a slight gap between it and the appended sprites. How do I go about limiting the speed that I can drag the sprite with ccTouchesMoved? This is the only solution I could think of to my problem. If anyone has another suggestion to prevent this sprite gap from happening I would appreciate it.

In ccTouchesBegan I loop through the sprites, mark the one that is touched(used for another part of game), and save the distance between the touch point and every other sprite.

touch = (CCTouch*)(touches->anyObject());
location = touch->getLocation();
for (int i = 0; i < grid->getGridSizeY(); i++) {
    for (int j = 0; j < grid->getGridSizeX(); j++) {
        button = grid->button(i, j);
        button->setDistanceX(location.x-button->getPositionX());
        button->setDistanceY(location.y-button->getPositionY());
        if (button->boundingBox().containsPoint(location)) {
            button->setTouched(true);
        }
    }
}

Then in ccTouchesMoved I loop through all the sprites again and set them to always be the same saved distance from the touch point.

touch = (CCTouch*)(touches->anyObject());
location = touch->getLocation();
for (int i = 0; i < grid->getGridSizeY(); i++) {
    for (int j = 0; j < grid->getGridSizeX(); j++) {
        button = grid->button(i, j);
        button->setPositionX(touchLocation.x - button->getDistanceX());
        button->setPositionY(touchLocation.y - button->getDistanceY());
        }
    }
}

This is the update method code only for a sprite moving off the left side of the screen. No point in writing all the sides until I get one side to work:

for (int i = 0; i < grid->getGridSizeY(); i++) {
    for (int j = 0; j < grid->getGridSizeX(); j++) {
        button = grid->button(i, j);
        //Replaces button if it goes off left side of grid
        if (button->getPositionX() < grid->button(0, 0)->getPositionX() - button->boundingBox().size.height / 2) {
            button->setPositionX(grid->button(grid->getGridSizeY() - 1, 0)->getCoord().x + button->boundingBox().size.height / 2);
            button->setDistanceX(location.x-button->getPositionX());
        }
    }
}


texts: Struggling with simple orthographic projection for a 2D setup

texts:
I'm trying to build a simple setup for 2D using SharpDX. Basically I want to supply my vertices in classic Cartesian coordinates: X-right, Y-up, starting with (0,0) in bottom-left corner. I've had similar experience with PSM (Sony OpenGL ES based framework for PS Vita and mobile), so I've used similar approach. The main work here is basically to construct a MVP transformation. Basic verification math on paper (800x600 screen):

so everything seems right here. So our target mvp matrix should match refT. The supplied point (50, 200) maps to (-0.875, -0.333) in clip space.

I used SharpDX-Samples\Desktop\Direct3D11\MiniCube as a starting point. I've modified it to leave a single cube plane, added texturing, everithing working fine so far. Then I replaced original coordinates with pixel-based one, and changed MVP calculation to this:

var model = Matrix.Identity;
var view = Matrix.LookAtLH(new Vector3(0, 0, -1), Vector3.Zero, Vector3.UnitY);
var proj = Matrix.OrthoOffCenterLH(0, form.ClientSize.Width, 0, form.ClientSize.Height, 0, 1);
var worldViewProj = model * (view * proj);
context.UpdateSubresource(ref worldViewProj, constantBuffer);

The worldViewProj is exactly as expected with math above. However there is nothing on the screen. I feel like I very close to solution but missing something. Any suggestions appreciated.

Complete main file gist. The part with ORTHO undefined is original sample code and it's working properly. With ORTHO defined is my new "pixel coordinates" approach which is not working as expected.

Update 1: as David suggested I've tried following modification:

var rDesc = RasterizerStateDescription.Default();
rDesc.CullMode = CullMode.None; // also tried CullMode.Front and CullMode.Back
var rState = new RasterizerState(device, rDesc);
context.Rasterizer.State = rState;

but it didn't seem to help in any way. I've also rearranged vertex order to be exactly in same order as in sample, but also with no success.


texts: Make openGL program only update every 1/60 seconds

texts:
I'm learning C++ and openGL and have this program as a result from tutorials and playing around. The problem is that the main loop is running at "full speed", making the program unnecessarily cpu intensive. I have managed to make it only perform rendering every 16.7 ms or so, but the outside loop that is waiting to render still is iterating as fast as my computer can handle.

This is the full main.cpp:
http://pastebin.com/KaCW7wZw

This is the main loop at line 95:

while (!terminate) {
    if (SDL_GetTicks() >= time_start + frame_rate)
    {
        time_start = SDL_GetTicks();
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT) {
                terminate = true;
                break;
            }
        }

        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        renderLoop(entities, &counter);
        SDL_GL_SwapWindow(m_window);;
        counter += 1.0f;
    }
}

I've tried googling and haven't found anything concrete (obviously), except that using some kind of sleep is bad design for these loops.

So how can I alter this to slow the whole thing down, and avoid having 100% cpu usage for a program that's not doing much at the moment?


texts: My question is, do I need the oculus rift development kit to develop games or can I do it with a standard pair of oculus rift,and if I can do it with a standard pair of oculus rift why does the development kit exist?


texts: OpenGL Array Texture generates black texture

texts:
I am creating a game using OpenGL that has many textured cubes. I am trying to use an Array Texture to load multiple textures from one file. I tried to setup my texture atlas; however, all that renders is a black texture. I'm not sure what exactly I am doing wrong.

Here is the texture loading code:

    // Load image
    stbi_set_flip_vertically_on_load(true);
    unsigned char *data = stbi_load(path, &width, &height, &nrChannels, 0);
    // Generate texture object
    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1, &textureId);

    glBindTexture(GL_TEXTURE_2D_ARRAY, textureId);

    // Actually load texture
    if (data) {
        glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, width, height, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
        //glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
    } else {
        std::cout << "Failed to load " << path << " texture" << std::endl;
    }

    // set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    // Free memory
    stbi_image_free(data);

Here is my fragment shader

#version 330 core
out vec4 FragColor;

in vec2 TexCoord;

uniform sampler2DArray my_sampler;

void main()
{
    FragColor = texture(my_sampler, vec3(0, 0, 1)) * vec4(1.0f);
}

Here is my texture file:

Does anyone know how I can solve my issue?


texts:
I am trying to implement a 3D mesh viewer with C++ and OpenGL ES 2. I am currently struggling with the calculation of the normals for the vertices, or at least I think that is where the problem lies... I tried to use the technique described in http://www.iquilezles.org/www/articles/normals/normals.htm to calculate the normals for my mesh. Here is the code that I came up with:

    // Calculate the non-unit normals for each face first
    glm::vec3 faceNorms[mesh->trigCount];
    for (std::size_t i = 0; i < mesh->trigCount; i++)
    {
        glm::vec3 vecs[3];

        for (uint8_t j = 0; j < 3; j++)
        {
            auto idx = (mesh->indices[i + j]) * 3;
            vecs[j].x = mesh->vertexFloats[idx];
            vecs[j].y = mesh->vertexFloats[idx + 1];
            vecs[j].z = mesh->vertexFloats[idx + 2];
        }

        glm::vec3 e1 = vecs[0] - vecs[1];
        glm::vec3 e2 = vecs[2] - vecs[1];
        faceNorms[i] = glm::cross(e1, e2);
    }

    // Now we need to sum the face normals for each vertex with larger faces carying more weight
    // due to their non-unit normals. We can then normalize the sum to get the vertex normals.
    for (std::size_t i = 0; i < mesh->vertexCount; i++)
    {
        glm::vec3 norm(0.0f);

        for (std::size_t j = 0; j < mesh->vertices[i].trigIdxs.size(); j++)
        {
            norm += faceNorms[mesh->vertices[i].trigIdxs[j]];
        }

        mesh->vertices[i].trigIdxs.shrink_to_fit();

        if (norm != glm::vec3(0.0f))
            norm = glm::normalize(norm);

        std::size_t pos = i * 3;
        mesh->normalFloats[pos]       = norm.x;
        mesh->normalFloats[pos + 1]   = norm.y;
        mesh->normalFloats[pos + 2]   = norm.z;
    }

At the moment I believe that all the importing code is correct as I thoroughly checked it out and tested what I could. The model is imported with arrays for all the vertex and normal floats and a float with indices. This is so that I can easily pass the data to OpenGL. As part of the importing I am keeping track of which faces share a vertex.

As far as I can see this code should be compatible with that in the article. I don't really have too much experience with OpenGL and the math involved to know if it should work in the first place though.

I tried to implement some shading using the information on http://www.learnopengles.com/android-lesson-two-ambient-and-diffuse-lighting/ but quickly ran into some trouble. It seems that the moment I try to translate the normals to eye-space, the dot product of the normal and the "light vector" becomes 0 and any form of lighting vanishes, leaving me with a black silhouette of my model. The below shader is an attempt to try an determine if the value is indeed 0. It is not a proper shader though so please don't comment on it being incomplete as to any specific lighting model.

uniform mat4 uModelMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjMatrix;

attribute vec4 aPosition;
attribute vec4 aNormal;

varying vec4 vColor;

const vec3 lightPos = vec3(10.0, 10.0, 10.0);
const vec4 baseColor = vec4(1.0, 0.5, 0.25, 1.0);

void main()
{
    vec3 norm = vec3(uViewMatrix * uModelMatrix * aNormal);
    vec3 objPos = vec3(uViewMatrix * uModelMatrix * aPosition);
    vec3 lightVector = normalize(lightPos - objPos);
    float cosine = dot(norm, lightVector) * 100000000.0;
    vColor = baseColor * cosine;
    vColor.w = 1.0;

    gl_Position = uProjMatrix * uViewMatrix * uModelMatrix * aPosition;
}

And the other half:

varying vec4 vColor;

void main()
{
    gl_FragColor = vColor;
}

This happens with any model that I try to load. I can post more information if needed but I have a feeling that my mistake is glaringly obvious (for an OpenGL expert of course) and somewhere in the code that I have here.

PS. If I use some basic non calculated shading like just using a semi-transparent color for each vertex then I can see that my model appears to be correctly loaded.


texts:
I am trying to implement this in Unity 4 Pro.

But I am stuck in the blending part. I don't understand how you could blend multiples textures/colors using multiples volumes on an object. How could you access those volumes in the shader and check for "collision"?

It's seems to be very similar to vertex/pixel lighting. But maybe I am wrong.

Here is the simple effect I am trying to create.


texts: Level design for puzzle game with a single mechanic

texts:
I'm developing a simple puzzle game where gameplay has a single mechanic where there is a limited amount of variation. I'm struggling to design levels that keep the game challenging/fun. I've added a bit of variation using time limits but overall it feels very repetitive.

On the other hand, there are games such as Flow which similarly has a  which have 1000+ levels and somehow they are unique/challenging enough for people to continue playing.

Are there any resources that cover level design for such a game?


texts: How do I implement camera axis aligned billboards?

texts:
I am trying to make an axis-aligned billboard with Pyglet. I have looked at several tutorials, but they only show me how to get the up, right, and look vectors. So far this is what I have:

target = cam.pos
look = norm(target - billboard.pos)

right = norm(Vector3(0,1,0) * look)
up = look * right

gluLookAt(
  look.x, look.y, look.z,
  self.pos.x, self.pos.y, self.pos.z,
  up.x, up.y, up.z
)

This does nothing for me visibly. Any idea what I'm doing wrong?


texts:
I'm using the following code in my viewDidLoad to load a sound:

NSURL * url = [NSURL fileURLWithPath:
   [NSString stringWithFormat:@"%@/Moto - Hit Sound.mp3",
   [[NSBundle mainBundle] resourcePath]]];
NSError * error;
hitSoundPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
hitSoundPlayer.numberOfLoops = 0;

Then I'm using this in a void method to play the sound:

if(CGRectIntersectsRect(main.frame, enemy1.frame)){
    [hitSoundPlayer play];
}

This does seem to work, however the first time the sound is played there is a lot of lag and the game stops temporarily. I'm using this same method for when in an IBAction and it works fine, it must be the fact that it's also detecting a collision that makes the sound lag. If I want to be able to play sounds quickly and on the spot without any sort of lag am I doing the right thing? Do I want to use another method?
I'm not using any frameworks like cocos2d. If you need to see any more code just ask.


texts:
Im aware that there a a couple of posts on this matter, but Ive tried all of them and none of them gets rid of my problem.

Im starting to get close to the end of my game so I bought a cabel to try it on a real phone, and as I expected my multitouch dosnt work. I use 2 joysticks, one to move my character and one to change his direction so he can shoot while walking backwards etc.

my local variable:

public void update(MotionEvent event) {
    if (event == null && lastEvent == null) {
        return;
    } else if (event == null && lastEvent != null) {
        event = lastEvent;
    } else {
        lastEvent = event;
    }

    int index = event.getActionIndex();
    int pointerId = event.getPointerId(index);

statement for left Joystick:

if (pointerId == 0 && event.getAction() == MotionEvent.ACTION_DOWN && (int) event.getX() > steeringxMesh - 50 && (int) event.getX() < steeringxMesh + 50 && (int) event.getY() > yMesh - 50 && (int) event.getY() < yMesh + 50) {
    dragging = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
    dragging = false;
}

if (dragging) {
     touchingPoint.x = (int) event.getX(); //used to calculate angle of sprites movement
     touchingPoint.y = (int) event.getY();

     //code for moving my character

statement for my right joystick:

if (pointerId == 1 && event.getAction() == MotionEvent.ACTION_DOWN && (int) event.getX() > shootingxMesh - 50 && (int) event.getX() < shootingxMesh + 50 && (int) event.getY() > yMesh - 50 && (int) event.getY() < yMesh + 50) {
    shooting = true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
    shooting = false;
}

if (shooting) {

    touchingPoint2.x = (int) event.getX(); //used to calculate sprites angle and get the correct direction
    touchingPoint2.y = (int) event.getY();
    // code for aiming
}

This class is my main-Views onTouchListener and is called in a update-method that gets called in my game-loop, so its called every frame.

Im really at a loss here, I've done a couple of tutorials and Ive tried all relevant solutions to similar posts.
Can post entire Class if necessary but I think this is all the relevant code. Just hope someone can make some sence out of this.

EDIT: both shooting and dragging joysticks work fine, but only when I press them one at a time, so I cant drag and shoot at the same time. I've looked around for a bit more and have understood that you need a MotionEvent.ACTION_POINTER_UP and MotionEvent.ACTION_POINTER_DOWN , but still dont know a way to implement it, some people use loops that goes through event.getPointerCount. Also with this Code my pointerId is always 0. To sum up: I want to be able to use both joysticks at the same time.


texts: How to calculate the Forward, Up, Right vectors using the rotation angles?

texts: As the title says, I have the pitch and the yaw of an object, How do i use them to calculate the forward, up, right vectors (like the ones in unity), I've searched everywhere and only could find the forward vector.


texts: How do I make the 3rd person camera follow the space ship in my Space Shooter game?

texts:
https://youtu.be/13HgaeZWlIA

I am making a 3D space shooter game using OpenGL and Bullet Physics. I am having a hard time with the 3rd person Camera though. If you take a look at the video above you can see that the camera follows the spaceship rotating on the X axis without a problem and rotating on Z axis also without a problem when the spaceship is is oriented towards the horizon and parallel to the ground. When I roll to the right and move the spaceship up I am totally losing it from the camera. The code for my camera is as follows:
float CalculateHorizontalDistance() {
    if (!mpPlayer) return 0.f;

    return distanceFromPlayer * glm::cos(glm::radians(-UpAngle));
}

float CalculateVerticalDistance() {
    if (!mpPlayer) return 0.f;

    return distanceFromPlayer * glm::sin(glm::radians(-UpAngle));
}

void calculateCameraPosition(float horizDistance, float verticDistance)
{
    if (!mpPlayer) return;

    glm::vec3 playerFront = mpPlayer->GetFront();
    glm::vec3 playerPos = mpPlayer->GetPosition();

    Position = playerPos + ((-playerFront) * distanceFromPlayer);

    UpAngle = 180.f - mpPlayer->GetRoll();
    //RightAngle = -mpPlayer->GetPitch();
    RollAngle =  mpPlayer->GetYaw() - 180.f;

    //float theta = mpPlayer->GetRotationY() + angleAroundPlayer;
    //float offsetX = horizDistance * glm::sin(glm::radians(theta));
    //float offsetZ = horizDistance * glm::cos(glm::radians(theta));

    //Position.x = mpPlayer->GetPosition().x - offsetX;
    //Position.y = mpPlayer->GetPosition().y + verticDistance;
    //Position.z = mpPlayer->GetPosition().z - offsetZ;
}

The above code is used to calculate the position and rotation of the camera. The commented out code was used to calculate the position based on trigonometrical calculations for the x and z sides of the triangle created from the camera position to the player position. This didn't work right because I could never set the camera behind the spaceship, only the position worked well.
On the non-commented out code I use as a camera position the player position - back vector * offset. This works fine for the simple purpose that the camera is always on the back side of the spaceship. I also update pitch and roll which works almost fine and here is where I need help mostly to get this right. I also never update the yaw of the camera.
This is how I get yaw, pitch and roll from Bullet Physics rigid body of the player (spaceship):
btScalar yaw;
btScalar pitch;
btScalar roll;
body->getCenterOfMassTransform().getBasis().getEulerZYX(yaw, pitch, roll, 1);

The following code is how the orientation of the camera is calculated :
void updateCameraVectors()
{
    // Yaw
    glm::quat aroundY = glm::angleAxis(glm::radians(-RightAngle), glm::vec3(0, 1, 0));

    // Pitch
    glm::quat aroundX = glm::angleAxis(glm::radians(UpAngle), glm::vec3(1, 0, 0));

    // Roll
    glm::quat aroundZ = glm::angleAxis(glm::radians(RollAngle), glm::vec3(0, 0, 1));

    Orientation = aroundY * aroundX * aroundZ;

    glm::quat qF = Orientation * glm::quat(0, 0, 0, -1) * glm::conjugate(Orientation);
    Front = { qF.x, qF.y, qF.z };
    Right = glm::normalize(glm::cross(Front, WorldUp));
    Up = glm::normalize(glm::cross(Right, Front));
}

and lastly how the view matrix of the camera is calculated:
glm::mat4 GetViewMatrix()
{
    // You should know the camera move reversely relative to the user input.
    // That's the point of Graphics Camera

    glm::quat reverseOrient = glm::conjugate(Orientation);
    glm::mat4 rot = glm::mat4_cast(reverseOrient);
    glm::mat4 translation = glm::translate(glm::mat4(1.0), -Position);

    return rot * translation;
}

Can someone help me fix the rotational problems that I am facing? I am open to modify also the Camera Class to make it work better with Bullet's quaternions instead of the Euler's angles that I am trying to use. Any code or ideas are very welcomed. Thank you for reading through.


texts:
This seems like a simple problem with an equally simple solution that is invisible to me.

I have a model that spawns at the origin and looks at my player model wherever it goes.

I would like it to move forward where it's going. Whenever I try to translate it, it disappears. What am I doing wrong and how do I fix it?

public override void Update()
{
    //Glo is a global class, where I store the player's world.
    targetShip = Glo.world.Translation;
    targetShip.Normalize();

    //Rotates the model to face the player's position
    rotation = RotateToFace(targetShip, pos, Vector3.Up);
    pos += Vector3.Normalize(targetShip - pos) * 20f;

}

public override Matrix GetWorld()
{
    // return  rotation * translation * world ;
    return Matrix.CreateFromQuaternion(rotation) * Matrix.CreateTranslation(pos);
}

UPDATE:
When I replace:

translation *= Matrix.CreateTranslation(direction);

with

translation *= Matrix.CreateTranslation(Vector3.Forward);

It now moves forward.

It does not correctly face me, however. It still thinks it's at the origin, and is rotating accordingly.

Here is the edited RotateToFace function
The original just returns a Matrix.

Quaternion RotateToFace(Vector3 O, Vector3 P, Vector3 U)
{

    //The direction we're facing.
    Vector3 D = (O - P);
    //Our relative Right.
    Vector3 Right = Vector3.Cross(U, D);
    Vector3.Normalize(ref Right, out Right);
    //Our back
    Vector3 Backwards = Vector3.Cross(Right, U);
    Vector3.Normalize(ref Backwards, out Backwards);
    //Our relative up
    Vector3 Up = Vector3.Cross(Backwards, Right);
    //Make a matrix out of all of these.
    Matrix rot = new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1);
    Quaternion rot2 = Quaternion.CreateFromRotationMatrix(rot);
    return rot2;
}

Draw code:

public void Draw(Camera camera)
{
    Matrix[] transforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect be in mesh.Effects)
        {
            be.EnableDefaultLighting();
            be.Projection = camera.projection;
            be.View = camera.view;
            be.World = GetWorld() * mesh.ParentBone.Transform;

        }

        mesh.Draw();
    }
}


texts: Spriting engine on mobile platforms, OpenGLES

texts:
I'm writing a basic spriting engine for a blackberry app, and I want to know the best way to draw tons of sprites using the glDrawArrays() command.

We have several sprites that move around the screen, and a bunch of sprites for background tiles.  Zelda-1 like tiling.

My first idea was to create a quad at the origin for every sprite that exists and glTranslatef it to wherever it needs to be.  But several hundred sprites to draw per frame, you only get to call this once for every call to glDrawArrays() so its not a good idea to call glTranslatef() on each sprite as you draw it.  That's the reason glVertex3f() was left out..

So I'm left with the option of maintaining a master vertex array and every time a sprite moves in the game, pushing the update to move the 4 vertices that represent its quad in the MASTERVERTEXARRAY.  I don't like this but it seems my only option.

What I'd really like is to be able to somehow create an array of "translation values" to use for every quad that gets drawn..

glTranslateArray( ... ) ;

But alas, no such thing exists.


texts: How can I read values from a running instance of an existing game?

texts:
I play an indie flight simulation game in Windows. I want to add a specific feature by means of creating a third-party add-on.

This apps will "link" and gather current altitude and position data from the game. My program will play sounds during certain altitude and airplane configurations (it's called GPWS).

I have seen the same thing done in an online RPG game where an external program counts damage dealt in the game (which requires peeking at the game's variables), so I think this is very possible.

My question is:

What is this data-gathering called? I googled many terms like hijacking or linking but the result is not what I meant.
How do i create program like this? I don't mind if its in other languages like Java or Visual Basic, but my main experience is in C++.


texts: Legality of remaking a game from a defunct company

texts:
Ive been a head from a now defunct company under someone else. And I directed coded and produced a game that reached around 99% completion but was never completed. I was wondering if its legal to remake the game or clone it with a different theme. I dont have a contract with the employer but I already prototyped the game before we developed it under the now defunct studio.

Any ideas on how legal is cloning or remaking it?

Also am I able to show of prototype games or footages from the defunct company?


texts: Is the position of a control relative to its anchor in Godot engine?

texts: I'm trying to place a button on the bottom right corner of the screen, so I tried to put all the Anchor parameters in the inspector to the value "End" but the position still needs to be specified relative to the top-left corner. If I try changing the margins in the inspector it kind of works but then I have to change all four margins taking into account the size.


texts:
I'm trying to make a relatively simple elevator (which essentially teleports the player), but I don't want it to instantly teleport them. I want the player to enter the collider, wait 2-3 seconds, and then do it to take make it seem somewhat more natural.

My code thus far:

using UnityEngine;
using System.Collections;

public class Teleporter : MonoBehaviour
{
    public GameObject TeleportTo;
    //public Material NewSkybox;

    void TimerInvoke()
    {

    }

    void OnTriggerEnter(Collider other)
    {

        Vector3 displacement = other.transform.position - this.transform.position;

        other.transform.position = TeleportTo.transform.position;
        other.transform.position += displacement;

        //RenderSettings.skybox = NewSkybox;
    }
}

Also if possible I'd like to stray away from coroutines. How should I do this?


texts:
I made a .GIF using sprite sheet animation, but I do not think it is working properly, because it shivers at the base. I made it in Photoshop Max Power.

How do I easily make perfect sprite sheets with images? I want to be able to add my images, resize them for my game and create a sprite sheet. Alternate software recommendation might be considered.


texts: Why don't I have some settings in GameMaker?

texts:
I recently bought GameMaker for Mac, however upon watching a few GameMaker videos I've realized that I don't have all options available.

For example, in "Sound Properties" in other videos people have the option to change the volume and the pan, whereas I don't.

Does anyone know why this is happening?