texts: How to obtain "gravity" and "initial impulse" given "desired time to reach max height" and "desired max height"?

texts:
I'm developing a 2d fighting game, using time steps based on frames ie, each call to Update() of the game represents a frame so, no variable time at all.

My jump physics code doesn't need to consider delta time, since each Update() corresponds exactly to the next frame step. Here how it looks:

double gravity = 0.78;
double initialImpulse = -17.5;

Vector2 actualPosition;
double actualVerticalVelocity;

InitializeJump() {
    actualVerticalVelocity = initialImpulse;
}

Update() {
    actualPosition.Y += actualVerticalVelocity;

    actualVerticalVelocity += gravity;
}

It works great and results in a smooth arc. However, it's hard to determine the values for "gravity" and "initialImpulse" that will generate the jump that I want.

Do you know if it's possible to calculate the "gravity" and "initialImpulse", if the only known variable is the "desired time to reach max height" (in frames) and "desired max height"?

This question should lead to the answer I'm looking for, but its current answer does not fit my needs.

UPDATE:

As @MickLH figured me out, I was using an inefficient Euler integration. Here is the correct Update() code:

Update() {
    actualVerticalVelocity += gravity / 2;

    actualPosition.Y += actualVerticalVelocity;

    actualVerticalVelocity += gravity / 2;
}

Only the very first step of the Update() will change and will move the object by initialVelocity plus the half of the gravity, instead of the full gravity. Each step after the first will add the full gravity to the current velocity.


texts: How can I place prefabs into a world and what's the best way to get them?

texts:
Hi all :) I'm making a 2D roguelike platformer and I want to make a load of hand crafted rooms and like spelunky place them around. When the player enters a room a script will go off. The script will know what exits the current room has and what entrance was used (Don't need to place anything where the player came from). I then have 2 options for choosing what rooms will work:

I can either have all the prefabs contain a script with a list of all the exits they have, then check that list for if the right one is there. I.E; Entered room from the left. Room has left, right and top exits. I can ignore the left as that's where I came from, I can ignore the bottom as there isn't an exit there but I need to check the arrays on the prefabs to see if they have right and top in them. After that I'd place the top one x units above and the bottom one x units below (I'd also check something wasn't there before placing over it).

The other option is to have 4 lists of prefabs. A list for top exits, bottom exits, left exits and right exits. Then look through those for what I need. Then I would place the blocks where they needed to be from there.

So, as the title says, what of those options would you use for picking and how can I then get the prefab I need and place it into the world. I'll use a "Centre" item for it and then place the centre of the prefab a certain amount to the side of the current rooms centre.

Thanks in advance for any help you can give :)


texts: Getting an object to move in another objects direction

texts:
I have a player and an enemy, both have x and y values, and I want to move the enemy to the player and have them 'touch' over time in a speed that I can determine, I tried calculating the angle between the enemy, the player, and the 0, 0 point on the canvas using trigonometry but it just doesn't work right, most the times the angle is Not A Number(NaN) or goes in a direction different that the player.
*The code is not in the same file, I copy pasted the relevant parts of the code and pasted them together.
Here is my code, any help would be greatly appreciated:

// Creating a visual triangle and storing the length of it's vertices distance(size)
    line(enemy.x, enemy.y, 0, 0);
    lineOne = dist(enemy.x, enemy.y, 0, 0);
    line(player.x, player.y, 0, 0);
    lineTwo = dist(player.x, player.y, 0, 0);
    line(player.x, player.y, enemy.x, enemy.y);
    lineThree = dist(player.x, player.y, enemy.x, enemy.y);
// Calculating the angle itself using the cosine rule
angle = acos((lineThree * lineThree + lineOne * lineOne - lineTwo * lineTwo) / (2 * lineThree * lineTwo));

//Function to move  the enemy(based on a suggestion made in this website)
this.move = function()
    {
        if(angle != NaN && angle >= 0)
        {
            this.x -= 2 * cos(angle) + sin(angle) * 2;
            this.y += 2 * sin(angle) + cos(angle) * 2;
        }
    }

The if statement that checks if the angle is not a NaN value is required because it happens a lot for some reason, it also checks if it is bigger or equal to zero, because if it isn't the enemy just doesn't show at all.

Thank you for your time!


texts:
So I'm fine with gameplay coding, but menus are something I'm still very new to.

I was watching Unity's own video on how to deal with Buttons and I thought I'd try mock up my own button animation much like they had. It works wonderfully, there's just one minor issue.

So a Button can go from 'any state', so either pressed, highlighted or normal (or disabled but I'm not using that). When I hover it works but it'll go straight back to normal once it's 'time'/'cycle' has completed. I figured that to fix this, I ought to add a transition between Highlighted and Normal.

This does work, providing I say that 'Normal' must be true before transitioning between the 2. Here's my issue however - when I click, the button hits pressed fine, then goes back to highlighted, and won't go back to normal unless I just click the background/anything that isn't the Button.

How can I get it to go straight to normal once the mouse is no longer on the button? I thought maybe a trigger collider with OnExitTrigger type function but that seems messy, isn't there a way to do this IN animator?


texts: How do I use screen-space derivatives to antialias a parametric shape in a pixel shader?

texts:
In Valve's Alpha Tested Magnification paper, it mentions using "per-pixel screen-space derivatives" for doing anti-aliasing. My understanding is that this is the ddx and ddy intrinsic functions in HLSL?

I'm trying to draw parametric shapes (for example a circle: x² + y² < 1) in a shader, and I don't know how to use this technique to correctly anti-alias the edge pixels of my shape. Can someone provide an example?

For completeness, here is an example of the kind of pixel shader I'm making:

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float dist = input.TexCoord.x * input.TexCoord.x
               + input.TexCoord.y * input.TexCoord.y;
    if(dist < 1)
        return float4(0, 0, 0, 1);
    else
        return float4(1, 1, 1, 1);
}


texts:
I'm attempting to check which object the user is hovering over.  While everything seems to be just how I'd think it should be, I'm not able to get the correct color due to the second time I draw (without picking colors).  Here is my rendering code:

public void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    camera.applyTranslations();

    scene.pick();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    camera.applyTranslations();

    scene.render();
}

And here is what gets called on each block/tile on "scene.pick()":

public void pick() {
    glColor3ub((byte) pickingColor.x, (byte) pickingColor.y, (byte) pickingColor.z);
    draw();

    glReadBuffer(GL_FRONT);
    ByteBuffer buffer = BufferUtils.createByteBuffer(4);
    glReadPixels(Mouse.getX(), Mouse.getY(), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    int r = buffer.get(0) & 0xFF;
    int g = buffer.get(1) & 0xFF;
    int b = buffer.get(2) & 0xFF;

    if(r == pickingColor.x && g == pickingColor.y && b == pickingColor.z) {
        hovered = true;
    } else {
        hovered = false;
    }
}

I believe the problem is that in the method of each tile/block called by scene.pick(), it is reading the color from the regular drawing state, after that method is called somehow.  I believe this because when I remove the "glReadBuffer(GL_FRONT)" line from the pick method, it seems to almost fix it, but then it will also select blocks behind the one you are hovering as it is not only looking at the front.

If you have any ideas of what to do, please be sure to reply!/

EDIT:  Adding scene.render(), tile.render(), and tile.draw()

scene.render:

public void render() {
    for(int x = 0; x < tiles.length; x++) {
        for(int z = 0; z < tiles.length; z++) {
            tiles[x][z].render();
        }
    }
}

tile.render:

public void render() {
    glColor3f(color.x, color.y, color.z);
    draw();
    if(hovered) {
        glColor3f(1, 1, 1);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        draw();
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }
}

tile.draw:

public void draw() {
    float x = position.x, y = position.y, z = position.z;

    //Top
    glBegin(GL_QUADS);
    glVertex3f(x, y + size, z);
    glVertex3f(x + size, y + size, z);
    glVertex3f(x + size, y + size, z + size);
    glVertex3f(x, y + size, z + size);
    glEnd();

    //Left
    glBegin(GL_QUADS);
    glVertex3f(x, y, z);
    glVertex3f(x + size, y, z);
    glVertex3f(x + size, y + size, z);
    glVertex3f(x, y + size, z);
    glEnd();

    //Right
    glBegin(GL_QUADS);
    glVertex3f(x + size, y, z);
    glVertex3f(x + size, y + size, z);
    glVertex3f(x + size, y + size, z + size);
    glVertex3f(x + size, y, z + size);
    glEnd();

}

(The game is like an isometric game.  That's why I only draw 3 faces.)


texts:
Has anyone used RageTools for Unity? What do you know about the performance? Is it more performant than using raster, for example with "puppet 2d" or the other way?
I'm developing mobile games, so performance is very important for me.
Thank you!


texts:
I've recently added an explosion in my game, for when enemies get killed, and it works fine and all, but the explosion wont "spawn" on the enemies x and y.
The problem is that I'm not drawing the bitmap from the center, but from its 0,0 position, so the explosion spawns at my enemies 0,0.
It's not like the explosion spawns at random places, it spawns around the enemies bitmap, but just not on the center, and it is really annoying to look at.

But if I try to change it so I add them at the center, It creates a really weird effect when rotating them that is hard to explain.

I cant use this: canvas.drawBitmap(bitmap, x - bitmap.getWidth/2, y - bitmap.getHeight/2, null);, or I'm just doing it wrong and missing something.

How I draw my enemies:

    public void draw(Canvas canvas) {
    canvas.save();
    canvas.rotate((float) rotater, x + (width / 2), y + (height/2));
    int srcX = currentFrame * width;
    int srcY = 0 * height;
    Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
    Rect dst = new Rect(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, src, dst, null);
    canvas.restore();
}

How I add my explosions:

    if (enemies.get(i).getHP() <= 0) {  //enemy death
        addExplosion(enemies.get(i).getX(), enemies.get(i).getY());

If you need any more info to be able to help, let me know.
Thank you!


texts: How to structure complex global game state?

texts:
Assume you're working on an RPG like Fallout and you have all sorts of flags and variables tracking the state of the world. Stuff like:

Talked to NPC X
Opened chest Y
Completed quest 1
Visited some dungeon
Defeated 30 goblins
etc.

You also want to save and load this information. My question is about the best way to structure this information. You could simply have a big global list of variables, but it's obviously better to break it up into smaller scopes. You could associate certain states with the current location, objects/NPCs, quests, or other scopes, but occasionally you have truly global information shared between multiple quests and locations. Furthermore, sometimes it's difficult to tell where the state belongs and you have to spend time thinking where to store it or find it.

The answers to this question suggest using a finite state automation, which might be fine for some examples like badge progress in Pokemon or keeping track of quests in a game, but it can get really complex if you have a more open game with a large number of states and hidden variables that influence multiple quests and interactions.

So to iterate, what are some good approaches for structuring game state? (particularly for RPGs and adventure games)


texts: How to make a changeable color constant for editor materials?

texts:
Due to the nature of a project I'm working on, the models I got have a bunch of redundant materials on them. I have to fiddle around with some of the colors, but every time I want to change the colors, I have to change each material to the exact same color.

Is there any way to declare some kind of swatch that I can change and have those changes just apply to the materials or anywhere else? For instance, in code, you'd just make a readonly Color mainColor, that you'd use wherever you need and could change at will. I'm looking for this kind of behavior in the editor itself.


texts: how to start the game without entering into menu screen

texts:
i am trying to play the game without entering to menu screen. i have placed only one scene. my ui and game both is placed within the same scene. in my game over screen i have two buttons. for home button i give

Application.LoadLevel (Application.loadedLevel);

by this code is loading the scene from the begning and its working perfectly. in my another button i want to play the game direcly without showing the main menu. so i tried

Application.LoadLevel (Application.loadedLevel);
launchGame();

but after loading the level my second line launchGame() is not working. how can i solve this problem? please help


texts:
I created a loading screen to display a loading animation as the next scene is loading. I load the next scene asynchronously with:

yield return SceneManager.LoadSceneAsync(scene,LoadSceneMode.Additive);

And also set Application.backgroundLoadingPriority = ThreadPriority.Low;, but the behaviour is still the same as a regular level load.

Am I missing something?

Expected behaviour:

Exit level, and fade out.
Loading screen appears.
Once load is done, fade loading screen out.
Fade in next scene.

What is happening:

Exit level, and fade out.
Loading screen appears, frozen
Suddenly new scene fades in.

Once the load starts, the game just frezees, like with a regular Scene load.

I read that you have to set allowSceneActivation = false, so you can fade the loading screen out, and then set it to true to let unity finish loading, but this completelly freezes my game, like the async operation never finishes loading.


texts:
I want to add lighting to an isometric game that I'm working on.

The closest I've come so far is to do a pass over the blocks on the floor and build up a light intensity matrix (based on how far each one is from the nearest light source). Then I've been rendering that with overlay compositing enabled.

This sort of works as a rough prototype, but there are some problems and I don't know whether they're inherent limitations of the way I'm storing the scene.

The floor blocks are stored in a 2d array and the world entities are stored in a list with their own 2d coordinates and height.

That means that if I overlay a light map like I did in the example earlier, the shadow only covers the tile. Entities on the tile are only partially effected by that tile's light value.

Here's an example where the blue tile is the overlaying light tile without blending turned on.

If that character was at the edge of the map, the top half of their body would be unaffected by the lighting.

I could trace rays out through the scene and mark the colliding faces with lightness values, but at that point, I'm not sure how I'd actually render that lightmap onto the screen.

How can I construct a light map that can be rendered over this scene?


texts:
I'm making an online game and considering whether to handle certain NPCs clientside. Is this common?

For example I play Elder Scrolls Online and it seems basic townspeople NPC locations aren't quite synced up with my friends. I guess it makes sense if they're only wandering around in a set area for that to be handled clientside right?

So my question is, should I go with this method, or are there any good reasons why I shouldn't? Any examples of games that do, so I can see how they handle it?.


texts: Optimal Way to Create Card Templates in Unity 2D

texts:
I have a couple questions involving software architecture and best practices in Unity. Although I have some programming knowledge, I am just starting with Unity and C#, and I would like some input from people with more experience than myself so I can learn Unity the right way and do not let bad habits take root.
In a nutshell: I am trying to put together a simple card drawing mechanic, where I would define a card layout (kind of like a class) and then initialise two-three at a time with data pulled randomly from a data source. Cards would have standard attributes like, cost, image, name, etc.
My first question is: what would be the optimal way to define the card template? Off the top of my head, I would say that it should be a prefab. But I am aware that there are other options as well, such as scriptable objects.
My other, related question, is: what would be a good way to store card data with future expandability in my mind. If my idea ever comes to fruition, I would like to release new card packs periodically, expanding the main card stock bit-by-bit. So, I am guessing, storing it in a simple JSON is probably not the best choice from a software architecture point of view.
Thank you for your answers!


texts: Fading alpha color with overall time. It's working but I need some help with some things to fix/change/add

texts:
This is more or less what I wanted, It's working in general but there are things to fix/add/change :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FadeInOutSaveGameText : MonoBehaviour
{
    public Animator animator;
    public Canvas canvas;
    public float fadingSpeed;

    private bool stopFading = false;

    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(OverAllTime(5f));
    }

    IEnumerator CanvasAlphaChangeOverTime(Canvas canvas, float duration)
    {
        var alphaColor = canvas.GetComponent<CanvasGroup>().alpha;

        while (true)
        {
            alphaColor = (Mathf.Sin(Time.time * duration) + 1.0f) / 2.0f;
            canvas.GetComponent<CanvasGroup>().alpha = alphaColor;

            if(stopFading == true)
            {
                break;
            }

            yield return null;
        }
    }

    IEnumerator OverAllTime(float time)
    {
        StartCoroutine(CanvasAlphaChangeOverTime(canvas, fadingSpeed));

        yield return new WaitForSeconds(time);

        stopFading = true;
        StopCoroutine("CanvasAlphaChangeOverTime");
    }
}

Things to fix/change :

Does the line StopCoroutine really work ? If I'm not using the helper flag and make break; inside the loop then the fading weill never stop.

Should I use a helper flag and break; only or also StopCoroutine ?

When the CanvasAlphaChangeOverTime Coroutine stop then the fading also stop at the same point it is. but I want it to finish fading first depending on the fading direction. If it was changing to the 0 then first finish fading to 0 then stop the Coroutine and same if it was more then 0.5 changing to the 1 then first finish changing to 1 then stop the Coroutine.

Things to add :

An option to change the fadingSpeed in real time while the fading is working ? How to do it ?


texts: How to draw a line of a given length towards a given object?

texts:
I wanna draw a line between two moving objects

I can't use:

cDrawLine(startPointCG, endPointCG);

because  the line must have a length. So I'm trying to measure the angle between those two points and then trace a line from start point towards that angle.

Something like this:

CGPoint endPoint = CGPointMake(startX + cos(direction) * 100, startY + sin(direction) * 100);

However, I can't manage to get it done properly. How do I calculate the angle direction?


texts: Mobile Game Development: Supporting Multiple Screen Resolution for iOS

texts:
Questions

When designing the graphics of the game (e.g. for iPhone): What is the resolution I should base it upon? Is it the smaller resolution (iPhone4 screen resolution) so that I could scale it bigger to bigger resolution devices later on or the bigger resolution (iPhone6+) so that I could scale it smaller for smaller resolution devices later on? Which solution would be the best to implement that will not distort the graphics?
I am creating a game now (endless runner type game) and I am using parallax backgrounds. What will be the best option in supporting multiple resolutions? Scale it so that it will look the same on every device but it might distort the image or reduces the viewing area of the game when scaled. Alternatively let the other parts of the background be seen on larger resolution devices making the graphics stay as it is but let users using larger resolution devices see objects that might not be seen on smaller devices. I am talking about the next part of the parallax background.

My question pertains to iPhone devices (iPhone 4/4s, iPhone 5, iPhone 5s, iPhone 5c, iPhone 6, iPhone 6 Plus) for now.


texts: How do I control which calculations are done on the CPU and which are done on the GPU?

texts:
My current understanding is that anything done in a shader file is done on the GPU, and anything done in my (Java, in my case) code is done on the CPU.

Is this an accurate description?


texts:
I'm not quite sure right how I should create my "Team System".
Lets say I have 2 teams with 4 players in there. The teams are Team Blue and Team Red.
A team knows the amount of its members, the amount of its points (each team will have points which the players gain for the team) and maybe some details for the HUD.

My solution right know would be to create parent class Team with the childs TeamRed and TeamBlue and add the players to the teams. (it would be also great to get a player's team through the player -> Example: Player.GetTeam() == TeamBlue?

But since Team red and blue are actually quit similiar and only have different HUD settings, I'm not quite sure about this design. Another possibility would be to just have a class Team and create the objects Team teamRed; & Team teamBlue;

what do you think guys?
any better solutions?


texts:
My question is simple yet it's got me wondering..I'm trying to limit my character's ActorLocation's X movement by checking it each tick. If it's larger or smaller than my desired value I set it back to my desired min/max.

I'm talking about a classical fighting game where I'm setting the "walls". I don't want to use actual walls as it won't let my character go to exactly my desired min/max.. Feels like a cheap way out, which doesn't work correctly anyway.

So I'm doing the tick-trick..

Am I being paranoid or this actually real bad practice? I feel like I might be tearing through CPU inefficiently and I would really want to avoid that.

I get that feeling especially because I'd be constantly getting and setting Y and Z for no reason at all. Since it's a fighting game I'd be doing it twice, too.

Many thanks in advance :)


texts: Remove previous scenes from memory in Unity 3d

texts:
I'm making a game in unity3d which I optimized as much as I can.

I've made different levels in each scene.

After a few scenes the game starts to lag on mobile devices. And works smoothly if application is restarted and game is continued from last scene .

How can I clear previously loaded scene in Unity3d or overcome the problem I mentioned above ?


texts: How do I make good guy attacks only hit bad guys and vice versa?

texts:
My game has many different type of good guys and many different type of bad guys.  They will all be firing projectiles at each other but I don't want any accidental collateral damage to occur for either alignment.  So bad guys should not be able to hit/damage other bad guys and good guys should not be able to hit/damage other good guys.

The way I'm thinking of solving this is by making it so that the Unit instance (this is javascript, btw), has an alignment property that can be either good or bad.  And I'll only let collision happen if the

class Attack

    boolean didAttackCollideWithTarget(target)
        return attack.source.alignment != target.alignment and collisionDetected(attack.source, target)

This is pseudo-code, of course.

But I'm asking this question because I get the sense that there might be a much more elegant way to design this besides adding yet another property to my Unit class.


texts: Changing background texture by drawing on it?

texts:
Actually I'm sorry for the title, I'm not sure which short phrase will describe situation best. I'm porting (or remastering, I don't know which word suits better, maybe both) a Win32, pure C, DirectX 8 game to XNA. Here is the problem I'm facing now.

The game background represents dirt through which player can dig, leaving the tunnels in it. The background is erased literally from a background bitmap array (which is static) by applying a "dig step" mask forming a new background picture:

From that little knowledge I have currently on XNA, I assume that it's hard to mimic this approach and modify a background texture in Update method. So I was thinking about storing an array of "tunnels" data and draw tunnels above background. This however seems not so elegant as the original approach. You see, tunnel form depends on direction, so I would need to store following information for a cell: 1) directions of tunnel (from 1 to 4), 2) dig amount (for each direction) ranges from 0 to 5.

So question is, what is a good way to implement that? Am I on a right way?

P.S. BTW anyone can try and see it in action!


texts: Pixel Art size for different resolutions

texts: What size I should make the UI elements (mostly buttons). How do pixel graphics look good on all resolutions? How would I get to know what size I need the buttons or other pixel graphics overall?


texts: [Unity]Avoid boucing when ground move down

texts:
I have a sphere & a quad, when the quad move down, the sphere fall after and bounce back continuously. I dont want to change my project setting like bounciness, gravity,mass and I need the sphere to move freely to jump between quad.
How can I do this, thanks


texts: ds_map_find_value returning number instead of array

texts:
Currently messing around on how to make a text engine in GameMaker and figured I would hold all my conversations in JSON format stored in a .txt file, which I'll convert into a ds_map and draw the text using the screen to the map.

Here's the JSON:

{"Neku": ["Hey Shiki.","Just trying to make this text engine thingy.","I really hope it works!"],"Shiki": ["Hey Neku! Long time no see!","What's up?","Wow thats cool!","I believe in you Neku!"]}

And here is the code I added into the create section of an empty object in a room:

str = ""
file = file_text_open_read("convo.txt")
str = file_text_read_string(file)
file_text_close(file)
map = json_decode(str)
if(ds_map_exists(map,"Shiki")) show_debug_message("A map exists") else show_debug_message("No map exists")
lst = ds_map_find_value(map,"Neku")
show_debug_message("What is lst?: " + string(typeof(lst)))

Now when I look at my console I see that a map does exist and the type of lst is shown to be a number and not an array as I had hoped. If I remove the [] in the JSON and just have one key-value pair the text shows up. If anyone could point me in the proper direction here I'd be grateful, apologies if this is a redundant stupid question.


texts: Crossfade Between Two Music Tracks in Pygame

texts:
My intention is to have two music tracks, which are similar in nature, fade between each other at various times.  When such a fade occurs, one music track should fade from full volume to muted in a short period of time, and, simultaneously, the other track should fade from 0 to 100 and continue playing from there.  They must be able to do this dynamically at any time - when a certain action occurs, the fade will occur and the new track will start playing at the same time index that the other one left off at.

This might be plausible by either using volume manipulation or by starting and stopping the music (however, it appears that only a "fadeout" option exists, and there is a lack of a "fadein" option).  How can I do this?  What is the best method, if any, that exists?  If it is impossible using Pygame, alternatives to Pygame are acceptable.


texts: C++/OpenGL Game - How to Make it Compatible with Screen Recorders?

texts:
I'm developing a 3D tower defense-like game in C++/OpenGL on Windows.

The problem I'm having isn't about the game itself (the game runs fine), but it's about using screen recording software to record gameplay.

For some reason, whenever I try to record the screen (I've tried both Camtasia Studio 8 and Fraps 3.5.9), it slows down the game (I'm not talking about just an FPS drop; the actual game timers run slower).

To show an example of what I mean, see the following screenshot: I ran two instances of my game at once (side by side), and recorded the righthand one using Fraps. As you can see in the image below, Fraps is causing the game time for the recorded instance to increase almost twice as slowly as it should.

I'm getting around 800-1000 FPS when running the game without Fraps recording, and around 300-400 FPS with Fraps recording. But playing the game with recording causes everything to happen in slow-motion, despite it running smoothly rendering-wise.

For timing I've tried using both the QueryPerformanceCounter() and timeGetTime() approaches - the slowdown still occurs using either.

Does anyone have an idea what might be causing this? Could it be because of the way I'm rendering with OpenGL?


texts:
I'm currently working on a 2D top-down survival game and I'm trying to figure out a good method for enemies to detect player sounds. For instance - if the player fires his gun it should play a sound (already implemented) and then enemies near the player should 'hear' the sound and react to it.

The obvious solution is to simply check a radius around the sound origin for enemies and flag them as having heard the sound. The issue here is that I have many buildings and walls and other objects that would normally interfere with sound. If I simply do a radius check then enemies will hear the player through walls and bulkheads.

The next obvious solution is to use raycasting. I cast a ray to every enemy within a radius of the origin of the sound and if the ray hasn't hit anything then the enemy can hear the sound. This method works, but I'm looking for something more natural.

What I'm hoping for is a method of having sound rays penetrate walls and lose intensity depending on the object. I'm using Farseer Physics and am currently working towards this implementation but there's one catch that I haven't figured out. If an enemy is around a corner then the ray will pass through the wall and lower intensity even though the enemy SHOULD be able to hear the sound loud and clear. I know this has to do with sounds bouncing off of other walls and echoing but I have no idea how to implement that without raycasting like crazy.

My question then becomes: Does anyone have a semi-realistic method of producing a sound in a 2D world, and having enemies react to it through, and around walls?


texts: How Do I Do Alpha Transparency Properly In XNA 4.0?

texts:
Okay, I've read several articles, tutorials, and questions regarding this.  Most point to the same technique which doesn't solve my problem.  I need the ability to create semi-transparent sprites (texture2D's really) and have them overlay another sprite.

I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this.  In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering.

In this case it seems to render the sprite below it blended with the alpha above it.  This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique.  Before I go any further I'll go ahead and paste my example code.

    public void Draw(SpriteBatch batch, Camera camera, float alpha)
    {
        int tileMapWidth = Width;
        int tileMapHeight = Height;

        batch.Begin(SpriteSortMode.Texture,
            BlendState.AlphaBlend,
            SamplerState.PointWrap,
            DepthStencilState.Default,
            RasterizerState.CullNone,
            null, camera.TransformMatrix);

        for (int x = 0; x < tileMapWidth; x++)
        {
            for (int y = 0; y < tileMapHeight; y++)
            {
                int tileIndex = _map[y, x];

                if (tileIndex != -1)
                {
                    Texture2D texture = _tileTextures[tileIndex];

                    batch.Draw(
                        texture,
                        new Rectangle(
                            (x * Engine.TileWidth),
                            (y * Engine.TileHeight),
                            Engine.TileWidth,
                            Engine.TileHeight),
                        new Color(new Vector4(1f, 1f, 1f, alpha )));
                }
            }
        }

        batch.End();

    }

As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state.  I'm almost positive that's my problem.  I don't want to BLEND the sprites, I want them to be transparent when alpha is 0.  In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending.  This is not a desired effect, I want the higher z-ordered sprite to fade out and not effect the color beneath it in such a manner.

I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole.

TIA


texts:
I'm having trouble inserting animation into my libGDX table cell.
I have a class which holds 2 tables, one on the left and one on the right. First table is for labels/buttons/other stuff. Second table is for animation, which should change if user clicks a button.

I've created Animation class which holds up different animations. The problem is that when I try to add an animation class into the table cell, I get an error because my Animation does not extend nor implement Actor class, thus I can't insert it into the cell. What should I do? How do you insert class of type animation into table cell?


texts: How to reverse the movement of the mouse on the X and Y axes?

texts:
I would like to know, how to do so that when moving the mouse to the right, it would go to the left and vice versa.

I looked for something related on the gamemaker page, but I didn't find what I'm looking for.

LINK:

https://docs.yoyogames.com/source/dadiospice/002_reference/mouse,%20keyboard%20and%20other%20controls/mouse%20input/index.html


texts: What is the difference between a hotkey and a shortcut-key in a game?

texts:
I was wondering: What is the exact difference (if there is any) between a hotkey and a shortcut-key in a game? Some games for example allow the player to bind certain actions to a specific key and call this hotkey other games allow the same thing and call it shortcut or shortcut-key.

When would you use which term? Or are they enterily swappable?


texts: How can I set up a flexible framework for handling achievements?

texts:
Specifically, what is the best way to implement an achievement system flexible enough to handle going beyond simple statistics-driven achievements such as "kill x enemies."

I'm looking for something more robust than a statistics based system and something more organized and maintainable than "hardcode them all as conditions." Some examples that are impossible or unwieldy in a statistics based system: "Slice a watermelon after a strawberry", "Go down a pipe while invincible", etc.


texts: Balancing a game about gladiatorial robot combat

texts:
Suppose a player can construct a robot built from various parts and each part costs money. How would you balance the cost of a weapon against its capabilities? What about balancing weapons against other parts?

The base case seems pretty easy: imagine the player can only buy weapons and everything else on the robot is the same. A machine gun that fires 1 bullet per second costs $100. A super machine gun that fires twice as fast could cost twice as much. But what about an ultra machine gun that has four times the range?

Now imagine the player can add other capabilities to the robot like better speed or armor. How do you relate the cost of a machine gun against the ability to move very quickly, or to be stealthed against radar?

I understand that there's a later stage of experimentation where costs and capabilities are adjusted, but where do you start from?


texts:
How can I draw a 2D sprite to look like it's at a particular placement in the 3D world?

My goal is to use this as loose items in the world.

Minecraft Example: https://lh6.googleusercontent.com/-HMk5tW_cI-Y/TiYx71XkwtI/AAAAAAAAAZQ/jeaTfiMW1Ow/2011-07-19_20.26.18.png


texts: Blender rigid body physics animation into Unity?

texts:
I'm stuck trying to get these cube objects to explode into chunks when destroyed in Unity. I've set up a physics sim in Blender of the effect I want, originally planning to replace the unbroken GameObjects with this fragmented one coupled with the explosion animation upon destruction. I guess it's not that simple.

I've tried "Bake to Keyframes" in blender and exporting as an FBX, but Unity imports each individual fragment with its own Animator/Avatar and a crazy amount of animations, which is almost useless. Any better ways to go about this?


texts: Why does accessing a uniform float make my shader more than twice as slow?

texts:
My fragment shader was significantly slowed down by a recent change, and I've been trying to understand why.

I isolated the main slow-down to accessing a single particular uniform float. If I include this line:

float not_used = my_uniform;

then the shader runs more than twice as slowly as it does without this line. The not_used float is never referenced again.

Why would this be happening? I hope to understand it so that I can try to come up with a workaround that runs more quickly.

I'm running this on a mac with Intel HD Graphics 3000. I'm measuring the performance by making OpenGL timestamp queries before and after executing my glDraw calls and looking at the ms intervals. I can provide more specs / details if it would be helpful in diagnosing the problem.


texts: Should each UI screen contain the list of screens on the stack or should I use a manager class?

texts:
I have a Screen class that encapsulates the updating and rendering of several distinct states, such as the menu, gameplay, and credits. A stack of screens exists on which the screens themselves need to be able to push new, and pop screens (imagine selecting "Start game" from the main menu, pushing the gameplay screen and popping the main menu screen).

I could have a ScreenManager class to babysit my screens but this would basically just be a wrapper around a list. I am therefore considering to pass each screen the std::list<Screen*> _screens and have them push and remove as they see fit. What I am worried about is overhead of copying this list around. If I recall correctly, since the list contains pointers to screens, the only thing I would be copying are the list of pointers, correct? And not the actual screens themselves.

Would this be an advisable way to go, or would you recommend creating a "wrapper class", such as a ScreenManager in any case?


texts: Calculate animation weights based on two variables

texts:
I am working on a custom engine and have been tinkering with animations using the Cal3D library. My previous experience with animations was based on prototyping a bit with Unity's Mecanim.

Right now, I'm trying to implement a character that can be idle, walk or run and is also able to point it's gun straight, up or down while doing any of the previous animations. As far as I know, this would require two different variables from which to calculate the weights of each animation, these are, the aiming angle and the speed of the player.

At first I thought about separating the hands and head of the player as a partial animation and do a 1DBlender (like the one in Unity) based on the aiming angle to interpolate between three different animations of the arms and head pointing up, straight or down. Then, for the rest of the body, interpolate with another 1DBlender based on the speed. While the solution works, I'm still not completely okay with it, as I cannot have blended animations for the arms and head based not only on the aiming angle but also on the speed (which would allo me to have things like having the head of the character slightly bobbing while pointing down and running and then having the head mostly still while idle).

My idea was to try to implement something similar to one of the 2DBlenders found in unity in such a way that I could have 9 animations (IdlePointingDown, IdlePointingUp, IdlePointingStraight, WalkingPointingUp, ...) and calculate the weight for each animations based on the two variables I have. The issue is that I don't have any idea on how to implement such blender. Could anybody give me any tips on what the pseudocode or general idea would be like, or recommend me a different solution?

Thank you very much.


texts:
I am using unity 2017.1.0 f3, Enlighten baking, with Generate lightmap UV ticked in import settings. Also the object has prioritized illumination and the light map resolution is high. An example of the artifact is shown.

The lightmapping settings is as follows.

The issue doesn't appear in Realtime illumination.

The object is marked static. Can someone help me?


texts: How can I make the screen scroll only when the character is close to the edge?

texts:
On the internet, I saw videos and tutorials about screen scrolling. But those only show how to keep the player always in the center of the camera.

I want my camera to scroll over the level, following the character, only when the character is within the 20% border of the screen.

So, when the player is not close to the edge of the window then the camera stays in place and not follow the player and when the player crosses this "scrolling line" the camera should smoothly follow hit. Let's say that my game window is 1000px wide and 500px high, but the game map is 3000px wide and 3000px high.


texts:
I'm attempting to make a Tetris clone and want to be as accurate to the games as I can. I found a chart that explains the speed curve that's supposedly used in games that follow the official Tetris guideline:
https://harddrop.com/wiki/Tetris_Worlds

1G = 1 cell per frame

Level 1: 0.01667G
Level 2: 0.021017G
Level 3: 0.026977G
Level 4: 0.035256G
Level 5: 0.04693G
Level 6: 0.06361G
Level 7: 0.0879G
Level 8: 0.1236G
Level 9: 0.1775G
Level 10: 0.2598G
Level 11: 0.388G
Level 12: 0.59G
Level 13: 0.92G
Level 14: 1.46G
Level 15: 2.36G

Another thing that might be worth noting is, like most Tetris games, my loop is updating at 60fps.

So given all this, there are two things that I'm having problems understanding.

1: The speed curve doesn't always translate to whole numbers.

For example, at level 2: 1 / 0.021017 = 47.5805300471. So every 47.5805300471 frames the game is supposed to drop the piece one row. Am I supposed to round these numbers? I can't process a partial frame so I don't understand why the speed curve comes out as a decimal.

2: Level 14 and 15 drop the piece more than one row per frame

Because it's dropping more than one row per frame, this would make some moves impossible in the game. For example, if I wanted to move a piece horizontally into a one cell space and the game is dropping the piece more than one row at a time, it will skip the row entirely and make the move impossible. Is this correct or am I missing something?


texts: Why do pixel shaders not let us read directly from the framebuffer or the depth buffer?

texts:
Letting me sample the framebuffer or the depthbuffer in the pixel shader would be an extremely useful feature. Even just being able to know the depth or the color of whatever is behind the current pixel would be useful.

Why does both OpenGL and DirectX not let me do this? I was expecting there to be some kind of hardware limitation, but alpha blending uses the color in the framebuffer for blending calculations, and the Z-test samples the depth buffer at the current location. Why not just expose these values to us directly? Can I hope to see this in the future?


texts:
How could I made a character jump with SFML in C++, a simple example could be very helpful.

Thanks in advance.

This is the code I currently have; how can I make the sprite jump?

#include <SFML/Graphics.hpp>
#include <iostream>
using namespace sf;

int main(){
    sf::RenderWindow ventana(sf::VideoMode(800,600),"mi ventana");
    ventana.setFramerateLimit(60);
    sf::Texture Image;
    Image.loadFromFile("tortuga.png");
    sf::Sprite sprite(Image);
    sprite.setPosition(-230,100);
    bool isPlay=true;
    bool presionarW(false);
    bool presionarA(false);
    bool presionarS(false);
    bool presionarD(false);
    //Controlar cualquier evento
    int x=30;
    int y=3;
    sf::Event miEvento;
    sf::CircleShape figura(10);
    while (isPlay)

    {
        //Eventos

        while(ventana.pollEvent(miEvento)){
            if (miEvento.type==sf::Event::Closed){
                isPlay=false;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::W){
                presionarW=true;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::A){
                presionarA=true;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::S){
                presionarS=true;
            }
            if (miEvento.type==sf::Event::KeyPressed && miEvento.key.code==sf::Keyboard::D){
                presionarD=true;
            }

        }

        //Logica del juego
        if(presionarW){
            sprite.move(10,-20);
            presionarW=false;
        }
        if(presionarA){
            sprite.move(-20,5);
            presionarA=false;
        }
        if(presionarS){
            sprite.move(0,25);
            presionarS=false;
        }
        if(presionarD){
            sprite.move(25,0);
            presionarD=false;
        }

        //Renderizado
        ventana.clear();
        ventana.draw(sprite);
        ventana.display();
    }
    ventana.close();
}


texts: Why is 2D light ray collision result getting inverted at specyfic angle

texts:
recently i've been working on 2D lighting for my game. I've created new little project, and I've encoutered a problem. The collision between light ray and the object is fine at angles 316-360 and 0-136 degrees. On the others, light gets inverted (it's gone form the source to the object, and it's present on the 'dark side'.
I know the code isn't efficient, it's just my concept project, I would like you just to help me understand what is going on in here.

Here's a function that checks for collision, for every single point in a light ray.

public Vector2 Intersects(Rectangle rectangle,SpriteBatch s)
{
    Point p0 = new Point((int)startPos.X, (int)startPos.Y);
    Point p1 = new Point((int)endPos.X, (int)endPos.Y);

    foreach (Point testPoint in BresenhamLine(p0, p1))
    {
        if (rectangle.Contains(testPoint))
        {
            s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black);
            return new Vector2((float)testPoint.X, (float)testPoint.Y);
        }
        else
        {
            final = testPoint;
                s.Draw(this.texture, new Rectangle(testPoint.X, testPoint.Y, 3, 3), Color.Black);
        }
    }
    s.Draw(this.texture, new Rectangle(final.X, final.Y, 2, 2), Color.Black);
    return Vector2.Zero;
}

// Swap the values of A and B

private void Swap<T>(ref T a, ref T b)
{
    T c = a;
    a = b;
    b = c;
}

// Returns the list of points from p0 to p1

private List<Point> BresenhamLine(Point p0, Point p1)
{
    return BresenhamLine(p0.X, p0.Y, p1.X, p1.Y);
}

// Returns the list of points from (x0, y0) to (x1, y1)

private List<Point> BresenhamLine(int x0, int y0, int x1, int y1)
{

    List<Point> result = new List<Point>();

    bool steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
    if (steep)
    {
        Swap(ref x0, ref y0);
        Swap(ref x1, ref y1);
    }
    if (x0 > x1)
    {
        Swap(ref x0, ref x1);
        Swap(ref y0, ref y1);
    }

    int deltax = x1 - x0;
    int deltay = Math.Abs(y1 - y0);
    int error = 0;
    int ystep;
    int y = y0;
    if (y0 < y1) ystep = 1; else ystep = -1;
    for (int x = x0; x <= x1; x++)
    {
        if (steep) result.Add(new Point(y, x));
        else result.Add(new Point(x, y));
        error += deltay;
        if (2 * error >= deltax)
        {
            y += ystep;
            error -= deltax;
        }
    }

    return result;
}


texts:
After upgrading to Unity 5.6, I've found my children canvases don't render right. I'm trying to figure out if this is a bug, or a new feature in Unity 5.6 that needs some adjusting.

Note the grey block on the upper left. What should be shown is a minimap, but per best practices, I was told to take frequently updating UI elements and put them on their own canvases. To compare this, here is an example from last week. The most notable difference is the transparent vs opaque view on the left. I did that in order to try to fix the problem, but it was on my todo list anyways.

Is there some setting that I should do to make the children canvases look right?


texts: How should I change the script so I will be able to change the transform height while the game is running and the transform is following?

texts:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Transform missionTarget;
    public Text textDistance;
    public Text textSpeed;
    public float lookAtRotationSpeed;
    public float moveSpeed;
    public float followRadius = 1.5f;
    public float fastRadius = 5f;
    public float speedBoost = 0.5f;

    void Start()
    {

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        float ms = moveSpeed;
        var distance = Vector3.Distance(transform.position, targetToFollow.position);
        // Compute a position no further than followRadius away from our target.
        Vector3 fromTarget = Vector3.ClampMagnitude(-lTargetDir.normalized, followRadius);
        Vector3 stopPoint = targetToFollow.position + fromTarget;

        // Compute a speed that's faster when far away and slower when close.
        float speedBlend = Mathf.Clamp01((distance - followRadius) / (fastRadius - followRadius));

        ms = moveSpeed + speedBlend * speedBoost;

        // Move as far as we can at our speed ms to reach the stopPoint, without overshooting.
        transform.position = Vector3.MoveTowards(transform.position, stopPoint, Time.deltaTime * ms);
    }

    private void Mission()
    {

    }
}

I mean the transform of the gameObject the script is on.
I want to keep the y position up all the way or at least make it finish moving on the ground or above the ground depending on my settings.
Now the transform the script is attached to the name is NAVI.
NAVI is by default position Y set to 5.94 :

Then the game start NAVI is moving to the target the kid_from_space in this case.
Kid_from_space position is at 0,0,0 when the NAVI getting close to the target NAVI position Y is 0 and the result is :

Therefore the NAVI is not on the ground and I also can't change it's Y position up or down. The NAVI is stuck at the Y 0 position. I want to be able to change the Y position up/down, for example if before the game is running I'm setting the Y position of NAVI to 5.94 or 6 or 21 I want the NAVI to stay at this position on the Y and not move down to 0.


texts: LibGDX - Managing and starting new levels

texts:
I have a Manic Miner style game where you need to collect all the items from a screen before you can advance to the next screen.

I have a screen class called "PlayScreen" wich starts out by loading a tiled map called "Level1.tmx", and contains the render and update loop.

public class PlayScreen implements Screen {
    ...
}

This screen is loaded by my main Game class, by calling SetScreen

setScreen(new PlayScreen(this));

So inside my PlayScreen, what is the correct way to restart the game but with a different level? I know I can pass through a new level number to get it to load a new tiled map, but this usually crashes.

Do I need to dispose of the screen and reload it again. I cannot find much information about this. Most LibGDX tutorials only cover a single screen or level, or have a menu screen in between. I just want to switch to the next level or room on demand, but cannot get it working.

Has anyone done this before - can you recommend a good way of doing this?

Regards

James


texts: How do I calculate vehicle rotation when two car wheels are on the ground to simulate gravity?

texts:
I'm writing some code to simulate a vehicle (tank or car) driving over a heightmap terrain. I'm not using a full physics engine, and just simply checking the height of the terrain at the 4 bottom corners of the vehicle bounding box for collision. The vehicle has a quaternion to represent rotation, and a 3D position.

I have orientation working if there are at least 3 wheels touching the ground (I can define a plane and determine the orientation from the normal), but what I'd like to do is react pseudo-realistically rotate the car if two wheels are touching the ground.

For example, if the rear two wheels hit the ground, I'd like to calculate a rotation to make the front of the vehicle drop until 3+ wheels touch the ground.

Obviously if I have two wheels intersection points, I have an axis, but I'm not sure how to manipulate the rotation and position to rotate around that axis when it's not central to the body.


texts: LibGDX efficient colored rectangle rendering

texts:
I'm creating a game in which I renderer around 1000 to 2000 solid colored squares per frame, 90% of which are the same size: ~4 px depending on the dpi. I am looking for the most efficient way to render them all using libGDX for Android and PC. Here's my past two approaches:

ShapeRenderer: This worked alright but I would encounter medium lag with a 1000+ squares.
Meshes tutorial: This caused heavy lag with only 100+ squares.


texts: Does Unity Pro Play Nice With 'Small' Teams

texts:
Does anybody know how well Unity Pro plays well with-in small teams?
Our team makeup is 2 programmers, 1 audio, and 2 graphics peps.

How easy is it for somebody to mess up a Unity project? The graphics and audio people will likely only have a simplistic knowledge of Unity, and mainly in regards to only there area.

Do the graphics/audio even need access to the Unity editor?

I've seen the Asset Server and it seems like a very bare bones versioning system.

Before people start telling me that they should just learn it (as I agree) this is a rather last minute student prototype project.


texts: Implementing multiplayer aspect of a simple HTML5 game

texts:
I've been thinking about this a lot. I am trying to implement a simple multiplayer game but I have difficulty figuring out how to "share the scene". For example, there are non-player entities like trucks and ideally I am thinking I will just send all the connected clients the bus location (x,y) and the rotation angle ,however, I am running into difficulty because the bus rotates each frame so I am wondering how I may achieve that on server-side?

It seems like a really tough nut to crack and I went over countless examples online and I think I just can't conceptually clarify how something like that can be accomplished.

Any ideas will be very appreciated.

EDIT: Somewhat related simplified question is this. How to simulate animation by sending (x,y, angle) from the server to the clients? Is it with setTimeout() on the server-side, what about each client having different frame-rate on their end?

EDIT2: Just to give one more example which I think would clarify. Consider a rotating triangle that all players should see. How do you accomplish this, do you adjust the angle in the server part of the code and then just emit to all players, because then the server side of code needs an update() for that object. Damn I hope I am not poorly expressing myself.


texts:
I want to form a Sphere given radius from blocks given size. And can't figure out the code / algorithm. Any help appreciated.

Edit: I dont wan't the Sphere to be filled, just the outer shell

Edit: I tried this

function ds(r)
    for tx=-r, r do
        for ty=-r, r do
            for tz=-r, r do
                if math.sqrt(math.pow(tx, 2)  +  math.pow(ty, 2)  +  math.pow(tz, 2)) <= r-2 then
                    Terrain:FillBlock(Vector3.new(tx, ty, tz), Vector3.new(1,1,1), material)
                end
            end
        end
    end
end

But it's very much iterations and so slow and odes the filling that is extra calls.


texts: Can someone explain me how rayCast works?

texts:
Im learning libgdx and one of the things that really confuses me its raycasting. I read a tutorial of how to use it and I understand it but I really want to know what's in the back. I searched for the source code of this method.

public void rayCast (final RayCastCallback callback, float point1X, float point1Y, float point2X, float point2Y) {   // FIXME pool RayCastCallback?
    world.raycast(new org.jbox2d.callbacks.RayCastCallback() {
    @Override
    public float reportFixture (org.jbox2d.dynamics.Fixture f, Vec2 p, Vec2 n, float fraction) {
        return callback.reportRayFixture(fixtures.get(f), point.set(p.x, p.y), normal.set(n.x, n.y), fraction);
    }
}, this.point1.set(point1X, point1Y), this.point2.set(point2X, point2Y));

}
How we can see this method calls itself recursively and returns a call to reportRayFixture of the callback variable. The thing that really confused me it's from where the code select the Fixture, and how its checks every fixture. Can someone explain me really how its works.

This its the source code page https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/World.java

I will appreciate it!


texts:
My problem with the collision here is more to do with how to decide which tile the player is in. Each quad of the map is 16 pixels squared (Vertex array), and the player moves in 1 pixel jumps. Because of this I cannot think of a way to decide which quad the player is in.

I am not sure if I am just missing something, but does anyone have an idea of how to do this?


texts: Calculating vertex_normals (vn) causes ugly lines C++/openGL

texts:
Im trying to procedurally generate planets for a project I'm working on. By adding noise to each vertex, I'm able to generate elevation, but without having updated vertice normals for my shader. It originally looked something like the picture below.

When I tried to recalculate the vertex normals, I got some ugly sharp lines, most likely as a result from the way I was parsing the model.

this is the code Im using to recalculate the normals:

for (auto &x : normals)x = vec3(0);  //zero normals
vec3 facenormal; //buffer

//indices is the faces/triangles indexed, in pairs of 3.
for (size_t i = 0; i<indices.size();)
{
    facenormal = cross(
        (shape[indices[i + 1]] - shape[indices[i]]),
        (shape[indices[i + 2]] - shape[indices[i]])
        );

    normals[indices[i++]] += facenormal;
    normals[indices[i++]] += facenormal;
    normals[indices[i++]] += facenormal;
}

for (auto &x : normals)x = normalize(x); //normalize adjacent faces

Basically I add up the adjacent faces to the vertices they belong to, then normalize the value they have.

Then, based on suggestions, I took a look at the parsing and made sure it doesnt share vertices in the indexing. This seems to remove the lines, but im still stuck flat shading?

But according to this, it should be accurate. So I'm still not fixing the problem. What is the correct formula to do the vertex calculation, if its not what I'm already doing.

Like user Kolenda suggests, I was not modifying values at the base-mesh level. but rather, doing them after loading the indexed copies. So, what I end up with is a combination of flat shading faces "shading" ghost vertice normals. Iterating over the faces on a mesh level, with the same formula, solves the problem.


texts: How do you map a 3D scene to a stero image pair?

texts:
I'm a novice.  I'm working in XNA studio with simple models.

How can I turn a 3D image into two images meant for the left and right eyes respectively?

Note: I'm not referring to "magic eye" - I'm wondering how you calculate the left and right images starting from the 3D scene info.


texts: How can I make units in my board game equal in stats yet unique?

texts: I am making a board game, but can't figure out how to make the units overall equal in their stats, with each one being individual?


texts: confusion in animating a sprite sheet using craftyjs

texts:
can anyone help me with this : http://jsfiddle.net/B5UsC/15/

you can see that the sprite animation is not rendering correctly and i am guessing that i am not using the exact width of the sprite ,i tried to change the width but also didn't work out

THE CODE :

// initialize the sprite
Crafty.sprite(52,123,"http://i.imgur.com/bkYVEe5.png", {
              Ryu: [0,0]
          });

// initialize the component
Crafty.c("RyuAnimation", {
              init: function () {
                  this.requires("SpriteAnimation,Keyboard")
                .addComponent("Ryu")
                .reel('idle', 1000, 0, 0, 9);
                this.animate('idle', -1);

              }

// creating the player
player = Crafty.e("2D,DOM,Canvas,RyuAnimation")
                    .attr({ x: 15, y: ch - 123, w: 52, h: 123 })
                    .start(3);

i am pretty sure the missing element is hidden somewhere in this code :

Crafty.sprite(52,123,"http://i.imgur.com/bkYVEe5.png", {
              Ryu: [0,0]
          });

but help me in figure out the real problem behind this confusion because i have no idea why this error in rendering is occurred


texts: Possible patterns for Registering event listeners of game entities with an event queue

texts:
I'm trying to integrate the idea of an event queue with a game loop that creates entities and responds to input. Is it better practice to submit entity reaction functions to the queue during input processing, or is there a way to generically broadcast events like text submission to the event queue? What would the class structures of entity and event queue look like to support the latter?

Specifically I'm looking for a response that includes code (any language) or pseudo code. Similar answers lack the specificity I need to make sense
of how fields on the structs or classes enable registration of listeners, broadcasting, and handling of events.


texts: What is a good algorithm for fractal-based procedural city layout?

texts:
Background

I run a minecraft server where I'm going to design a starter city of fairly large scale. I have a series of things, like rule signs and mob cages, I would like to put in buildings there. The city itself will be extremely large and spread out, preferably up to 1000 by 1000 blocks in size.

The buildings themselves will be have cube or rectangular footprints that are based on a certain base cube, like all multiples of 3 blocks. The streets and distance between the buildings will be preferably 5-11 blocks wide, depending on the importance of the street.

When I begin the plan for the city, I will know exactly how big I want the buildings to be and how many there will be.

The Problem

The problem is designing the layout for the city. Obviously with something of such a scale, and me coming from a programming background rather than an urban planner background, it's quite challenging to even begin to wrap my head around the problem.

The problem specifically is that I want the city to look as natural as possible. Of course this would be fairly easy to build on a simple grid pattern, but I want to avoid a grid, or anything that looks like a grid, as much as possible.

The Question

What algorithms might I be able to pursue to be able to help me design it using code? I was thinking that it would look most natural if I used fractals in some way, as minecraft uses fractals already in its terrain generation, and a city seems to grow in a fractal pattern naturally.

I think it's similar in some ways to a tetris playing algorithm, so if anybody has solutions that exist down that direction then it would help also. I'm picturing something where I'll be able to define the shapes that I want to use, and the software then iterates until it finds the most "optimal" solution for even distribution of buildings.
Does something already exist to help me solve this problem using python, preferably in a visual way using pygame?

Naturally this also has interesting implications for city generation in general in game design, so I'm very excited to see what the best solution is.

edit
To be clear, I'm just looking for the layout at this point as the buildings will be designed and built in game.


texts: Why does masked animation look so strange?

texts:
I have an idle and a shooting animation.
Both animations are perfectly tailored to my model.
The idle animation looks like this:

And the shooting animation looks like this:

I have 2 animation layers:
The "Base" layer plays the idle animation.
The "Pistol Shooting" layers plays the pistol shooting animation, and it has an avatar mask because it should only influence the upper body.
The results however look like this:

What might be wrong here? What could I check?


texts: How can I remove inventory items in a Bukkit plugin?

texts:
I am making a Bukkit plugin that takes the player to a "FunZone" and allows them to do just about anything. I don't want data transferred between the two worlds. So far I have got most everything stopped. Here's the problem code:

            Integer normInvSize = player.getInventory().getSize();
            Integer i = 0;
            for (i=0; i<normInvSize; i++) {
                ItemStack item = player.getInventory().getItem(i);
                pConfig.set(player.getWorld().getName()+"Inv."+i.toString()+".amount", item.getAmount());
                Short durab = item.getDurability();
                pConfig.set(player.getWorld().getName()+"Inv."+i.toString()+".durabillity", durab.intValue());
                pConfig.set(player.getWorld().getName()+"Inv."+i.toString()+".type", item.getTypeId());
                player.getInventory().removeItem(new ItemStack(item.getType(), item.getAmount()));
            }

I have everything set up how I want it but I get stray items following me between the worlds. The line

player.getInventory().removeItem(new ItemStack(item.getType(), item.getAmount()));

does not remove all of the inventory. I want some code that will remove all inventory items (I've handled armor already). I already have a way to restore the inventory later, but my code currently won't remove everything. For example I can end up transfering some stone tools from the "FunZone" to the normal world, which I don't want.


texts: How can I write a terrain into a .raw file?

texts:
I want to generate a terrain through Perlin noise and store it into a .raw file.

From Nehe's HeightMap tutorial I know the .raw file is read like this:

#define MAP_SIZE        1024

void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap)
{
    FILE *pFile = NULL;

    // Let's open the file in Read/Binary mode.
    pFile = fopen( strName, "rb" );

    // Check to see if we found the file and could open it
    if ( pFile == NULL )
    {
        // Display our error message and stop the function
        MessageBox(NULL, "Can't find the height map!", "Error", MB_OK);
        return;
    }

    // Here we load the .raw file into our pHeightMap data array.
    // We are only reading in '1', and the size is the (width * height)
    fread( pHeightMap, 1, nSize, pFile );

    // After we read the data, it's a good idea to check if everything read fine.
    int result = ferror( pFile );

    // Check if we received an error.
    if (result)
    {
        MessageBox(NULL, "Can't get data!", "Error", MB_OK);
    }

    // Close the file.
    fclose(pFile);

}

pHeightMap is one-dimensional, so I don't understand how I would write the x,y correspondence to a height value.  I was planning to use either libnoise or the noise2 function on Ken Perlin's page, to make each value in a 1024x1024 matrix correspond to the height for the point, but the .raw file is stored in a single dimension, how can I make x,y correspondence work there?


texts: How can I access the translation part of a skinned Model object's bone transformation?

texts:
I have an animated Model, which I process with the SkinnedEffectProcessor.
How I can access translations of that model during animation?

It's always a BoneTransform I am working with, but I'd like to know which X, Y and Z values are currently changing.

So, during the update I added this line

Debug.WriteLine(_model.GetBoneTransform("RootNode").Translation.ToString());

but all it outputs is

{X:0 Y:0 Z:0}

when I trigger the jump-animation. I'm expecting the Y value to go up, since the model is jumping in that animation.


texts: How do I get the touch event on a body in JBox2d

texts: I have various bodies rotated at some angle with the help of Box2d in LibGDX. What I want is to destroy the body when I click on it, but the problem is that I am not able to get the area definition of the body so that I can check whether my touch point lies inside the body. I tried using actor and its hit() method but it's working only if I don't rotate it. As far as I know, once I rotate the body, its bounds are not rotated.  How can I check the Touch event in a Body?


texts: How can I make the transform to keep moving the direction it was moving when pausing and then resuming?

texts:
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Experimental.GlobalIllumination;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Moving : MonoBehaviour
{
    public Transform destination;
    public float moveSpeed = 5f;

    private Coroutine movementCoroutine;
    private bool pause = false;
    private Vector3 startPosition;

    private void Start()
    {
        startPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            pause = false;
            MoveToDestination();
        }

        if (Input.GetKeyDown(KeyCode.S))
        {
            pause = true;
        }
    }

    private void MoveToDestination()
    {

        // if the coroutine is still running, stop it
        if (movementCoroutine != null)
        {
            StopCoroutine(movementCoroutine);
        }

        // start the coroutine
        movementCoroutine = StartCoroutine(MoveToDestinationCoroutine());
    }

    // the coroutine
    private IEnumerator MoveToDestinationCoroutine()
    {

        // while this object is not at the destination
        while (transform.position != destination.position)
        {
            if (pause)
                break;
            // move it towards the destination, never moving farther than "moveSpeed" in one frame.
            transform.position = Vector3.MoveTowards(transform.position, destination.position, moveSpeed);

            // wait until next frame to continue
            yield return null;
        }

        while (transform.position != startPosition)
        {
            if (pause)
                break;
            // move it towards the destination, never moving farther than "moveSpeed" in one frame.
            transform.position = Vector3.MoveTowards(transform.position, startPosition, moveSpeed);

            // wait until next frame to continue
            yield return null;
        }

        StartCoroutine(MoveToDestinationCoroutine());
    }
}

I'm using the bool flag pause variable to pause and resume.
Pressing space to start moving then pressing s to pause and then space to resume the movement from the current paused position.
The problem is when it's resuming the movement it's not moving to the direction it was moving. It will resume the movement always to the left side even if it was moving to the right.
space key to start and resume and s key for pause.
Update :
I changed the pausing part to this :
private IEnumerator MoveToDestinationCoroutine()
    {
        // while this object is not at the destination
        while (transform.position != destination.position)
        {
            if (pause)
            {
                yield return null;
            }
            else
            {
                // move it towards the destination, never moving farther than "moveSpeed" in one frame.
                transform.position = Vector3.MoveTowards(transform.position, destination.position, moveSpeed);

                yield return null;
            }
        }

        while (transform.position != startPosition)
        {
            if (pause)
            {
                yield return null;
            }
            else
            {
                // move it towards the destination, never moving farther than "moveSpeed" in one frame.
                transform.position = Vector3.MoveTowards(transform.position, startPosition, moveSpeed);

                yield return null;
            }
        }
    }


texts: Spawn a gameobject from list when grip button is clicked?

texts: I wanted to spawn gameobjects from the list one by one when the grip button in the controller is clicked. I have attached my code  and the inspector  which contains the list of gameobject but the code is not working. Need Help


texts: InvalidOperationException when peeking from a stack within custom editor

texts:
I've got a simple state machine for handling game states which works using GameObjects that I enable/disable in order to switch the states. Since some states can be loaded additively (such as the pause menu), I'm using a stack to manage the currently active ones.

public class GameController : MonoBehavior {

    private readonly Stack<GameObject> _stateStack = new Stack<GameObject>();

    public GameObject ActiveState {
        get { return _stateStack.Peek(); }
    }

    public void SetState(GameObject newState, bool isAdditive = false) {
        if(newState = null || newState == ActiveState)
            return;

        if(!isAdditive) {
            while(_stateStack.Count > 0)
                PopState();
        }

        if(!newState.activeInHierarchy)
            newState.SetActive(true);

        _stateStack.Push(newState);
    }

    public void PopState() {
        var gameState = _statStack.Pop();
        if(gameState != null)
            gameState.SetActive(false);
    }

}

Now I'd like to have a custom editor which allows me to see and set the currently top-most active state.

What I did was this:

[CustomEditor(typeof(GameController))]
public class GameControllerEditor : Editor {

    public override void OnInspectorGUI() {
        DrawDefaultInspector();

        var controller = target as GameController;
        if(controller == null)
            return;

        var newState = EditorGUILayout.ObjectField("ActiveState", controller.ActiveState,
              typeof (GameObject), true) as GameObject;
        if (newState != controller.ActiveState)
            controller.SetState(newState);
    }

}

However, the custom editor is never visible and in the console, I see the following exception:

InvalidOperationException: Operation is not valid due to the current state of the object
System.Collections.Generic.Stack'1[UnityEngine.GameObject].Peek()

What does this even mean? What state? Is the stack not initialized? How does Unity instantiate MonoBehaviors when applying a custom inspector?


texts: Do I need to rewrite my HLSL shaders when porting from XNA to MonoGame?

texts: I'm looking at porting an XNA project I have to monogame, but I have a fair number of HLSL shaders.  It seems that Monogame for PC uses OpenGL as the rendering backend, and I'd rather not have to rewrite all of my shaders during the port.  Am I wrong about this, and will I need to rewrite my shaders during the port?


texts: What are the advantages and disadvantages of different grids in a turn-based strategy-game?

texts: The two most common types are using hexagons and squares. My question is rather concerned with game design. Why are specifically those two found so often? What are disadvantages that speak against using other polygons such as triangles, pentagons or octagons?


texts: Adding Score to score canvas after collision

texts:
Simply a player has to move through pipes falling down, once the player moves through the gap it should add a score and increase the scoring after each pipe the player goes through, pretty basic.

I have made a prefab object and it is a block with a collider on it and another collider that acts as a trigger behind it stretched out so it can be accessed on both sides. I then added to the main scene canvas >> textmeshpro>>> added a script with the following code however, when the player hits the collider the score does not increase in the scene. But if I remove the GetComponent then it increases by increments of 4 in the inspector.

using System.Collections.Generic;
using UnityEngine;

public class Game : MonoBehaviour
{
    public int Score = 0;

    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        GetComponent<UnityEngine.UI.Text>().text = Score.ToString();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        AddScore();
    }

    void AddScore()
    {
        Score++;
    }
}


texts: best structure to handle entities in an entity component based game engine

texts:
I am trying to develop a 2D entity component based game with multiple layers as tilemaps (front or back from the scene).

I currently handle the tilemap layers in a 3 dimension array[z][y][x]. Each tile from the map is an entity and have a positionComponent which define x, y and z. The array structure is very convenient to update and render only visibles entities (in the viewport).

I have also added an 1 dimension array to handle the ennemies and items. The problem is that I want to fusion the tilemap and ennemy array in one single structure (I want to update and render entities within a single strcture).

As the entities already have a positionComponent defining x, y and z, is there a good way to get rid of the 3 dimensions array without loosing performance?

Ideal will be to be able to do something like entities.get(z, y, x).


texts: Is there a difference between using one large mesh with 100k polygons and using 1000 meshes with 100 polygons each?

texts:
I'm planning on creating a first-person shooter for mobile. Now I know that fps games usually have a lot of meshes in the scene (trees, buildings, terrains, etc.). So I've been looking at a lot of Unity optimization tips. One thing I've noticed is that they always say "If you have a lot of objects in your scene, then each mesh must have low polygon count".

But how exactly does this help? If I have a lot of houses in my scene and I ensure that each house has very few polygons, wouldn't the total number of polygons in my scene be affecting the performance anyways? Or will my scene be rendered differently now that I've broken up the total polygon count into multiple parts?


texts: Steering behaviours that gaurentee not to hit something

texts:
I'm really struggling how people make steering behaviours that guarantee a given agent will never hit something.

I want to have a flocking algorithm that the agents can follow each other and also avoid each other and avoid objects in the game.

I know how to detect and find a vector for them to change course, but not how to guarantee they adjust in time to make the change before crashing into the object.

Whats the correct way to approach this stuff?


texts: How do I detect whether mouse (or touch) is being pressed over thecurrent gameObject in Unity 5?

texts:
I have a Canvas set as Screen Overlay, and an Image there. I want my image become an 8-direction custom pad, so I wanted to make a component script for the image.

In such behavior I would like to detect, on each frame (Update()) whether the mouse (or touch 0) is being pressed over the current object, say:

public class MyBehavior : MonoBehavior {
    void Update() {
        if (Application.isPlaying && Input.GetMouseButton(0)) {
            // TODO Verify the mouse is pressing over this.gameObject
        } else if (Application.isMobilePlatform && Input.touchCount > 0) {
            Touch touch = Input.GetTouch(0);
            if (touch.phase != TouchPhase.Canceled && touch.phase != TouchPhase.Ended) {
                // TODO Verify the touch is pressing over this.gameObject
            }
        }
    }
}

What I need is:

Determine the pressed-over UI object is actually this.gameObject and not one which is overlapping in front.
Determine the position of the click, in the same coordinate space as the image being clicked.
My goal is to calculate the appropriate direction of the click (angle) wrt the pivot of the image. I will process that direction value. I will also calculate the appropriate distance to the pivot, and process it.

How can I achieve that goal?

(Notes: The test I want to do for standalones and mouse are actually for debug purposes)


texts:
I want to rotate my rectangular sprite with circle body.
The problem is the body doest not attached to the centre of the sprite. This was the default behaviour of the body and sprite.

But I want that circle body attached in the bottom of the rectangle and when rotation happen at that time rectangular sprite always attached with the body at the bottom and during simulation it change its angle and position according to this only.

I try to write question in words if I don't able to understand you then know me then I post a picture of my problem here.

Although I know that cocos2d has setAnchorPoint method available so similar task become easily but what about my engine that right now I was using - AndEngine. So be relevant to this game platform.

Also thanks in advance for efforts you take.


texts:
I'm trying to create a Killing Floor map and i have the latest Unreal Engine but i dont know how to export my map to Killing Floor.
Where can i find the correct version of Unreal Editor ?
How can i export my map with current version ?


texts: Entity component system: how and where store pointers to system resources or third-party lib's objects?

texts:
I'm migrating my game pet-project to ECS. I use C# (custom-made engine, not Unity). It goes pretty well, but one big thing is making me worry.
This is how and where to store pointers to system resources or third party libraries' objects?
For example, I have object with Transform and RenderModel component.
Transform contains data like matrices, quaternions etc (like described in any ECS paper :)
RenderModel contains path to FBX scene and some data how to render this model (materials, overrides, flags, scaling, etc).
For model rendering I use existing rendering library. To render the model I need to create object, add it to this library, update its transform if necessary and destroy it when I don't need to draw this model any more.
The question is where to store pointer to such rendering objects?
I see three approaches:

Any component that holds such resources implements methods OnAdd and OnRemove which are called when component added or removed respectively. On addition the component create lib's object and destroys it on removal. I've focused on this approach because it's pretty straightforward and simple to implement. Main drawback of such approach that I need to implement some kind of workaround to feed transformation to this models.

Systems are stateful and keep tracking of component addition and removal. When given combination of components is added (i.e. RenderModel and Transform) system that handle object drawing creates internal representation of the model and destroys when components are removed. Main drawback that I have no idea how efficiently track multiple component addition and removal.

Some kind of "imperative" approach. For each entity with RenderModel and Transform components system calls method like DrawModel(...). At the end of the frame the internal representation is destroyed and created again on next frame. Such approach looks like most convenient approach from game logic view, but suffer from obvious performance issues, because rendering library might build internal structures, cache visibility data, use interleaved shadow maps etc. Furthermore, updating this systems in parallel threads obviously will become nightmare.

Same issues I've also encountered with physics library and FMOD sound, because such libs also offer some long-living objects (non-POD) and build internal data structures.
Could you suggest better approach to solve such issue?
P.S. I use custom (made from scratch) engine (not Unity)


texts: Allow code after a bugged line to continue without use of try and catch

texts:
My problem is with C# in unity, but I think the problem can be applied to all coding languages.

For example I have a start function/event that may initiate many things. Some lines of code may issue a bug but I want to allow new lines of code run after that without having to encapsulate every line of code with try and catch. Is there any common solution for this that I'm missing?


texts: How to make a triangle pixellated with GLFW?

texts:
How can one make a triangle look pixelated without modifying the size of the window in GLFW3?

Preferably, I'd like to accomplish this without the use of shaders. For example, by setting the size of the frame buffer to be 1/8th the size of the window.

I've created an Xcode test project for this and tried setting a small window size to create a small framebuffer, then changing the window size to be big afterwards, but the framebuffer size always changes to match the window size.

Example project output:

Desired output:


texts: What types of matrices are needed for game and graphics programming?

texts:
I am writing a 3D math library for general game development and want to know what type of matrix classes I should include. Is just a 4x4 matrix enough, or must I provide 3x4 and dedicated rotational matrices?

According to this

  In order to use the vector registers of modern CPUs (SSE, Altivec, SPUs) you have to pass 4x 32 bit floats anyway (its a 128 bit register), plus you have to take care of the alignment, usually 16 bytes. So you don't have the chance to safe the space for the 4th component anyway.

and from Game Engine Architecture

  The rightmost column of an aﬃ ne 4 × 4 matrix always contains the
  vector  [ 0 0 0 1 ]T . As such, game programmers oft en omit the
  fourth column to  save memory. You’ll encounter 4 × 3 aﬃne matrices
  frequently in game math  libraries.

Since 4x3 matrices are just created for convenience and since you need 128 bits to use the vector register, would it be best to just have a single 4x4 matrix class handle all needed matrix operations?


texts: How to render 3d object as 2d with different angles

texts:
I wanted to make a ship as a 3d object and import it with an atlas file to my 2d libgdx project with different angles like I saw it by another game.

And I was wondering if there is a specific software which should be prefered to make those things.

Where can I create the 3d objects and export them into a big png + atlas file?


texts: How to adjust the width of a LineRenderer

texts:
I wrote a code that draws a line by mouse movement. I am searching for some way to give it pencil style and head and end of the line have thinner width.
As we know the LineRenderer draws the line between points. How can I access first and last point elements to set the width of them and how can I do that?


texts: A more sophisticated ball-paddle collision algorithm for Breakout?

texts:
I have a simple breakout game I'm working on. The collision code is solid; things bounce as they should and don't pass through things or do other funkiness, but the reflection is a bit simplistic. As a result, it's easy to get into a state where the ball gets stuck in a loop such that the last blocks cannot be hit without dying to break the loop.

Currently, the paddle collision code reflects the Y speed, and mirrors the X speed depending on what side of the paddle it hits:

        // Check for paddle collisions
        if ((m_ball.rect()).intersects(m_paddle.rect())) {
            double ballCenter = m_ball.rect().getX() + (m_ball.rect().getWidth()/2);
            double paddleCenter = m_paddle.rect().getX() + (m_paddle.rect().getWidth()/2);

            m_ball.setSpeedY(m_ball.speedY() * -1);

            if (ballCenter > paddleCenter) {
                m_ball.setSpeedX(Math.abs(m_ball.speedX()));
            } else {
                m_ball.setSpeedX(-Math.abs(m_ball.speedX()));
            }
        }

Is there any way I could make the algorithm more "interesting", and tighten up the control so the ball doesn't keep get stuck bouncing in the same square?


texts: What design pattern should be used when there are a lot of different possible jobs?

texts:
Some background information on what I am trying to accomplish. I am creating the game in Unity using C#. Basically, I am trying to create an RPG type of game where it really harps on the idea of a lot of different possible classes/jobs(I will call them jobs so not to confuse anyone). Basically, every job will have its own unique set of skills and can only do certain tasks, not dissimilar to a lot of games out there. However, the way I see most of the advice given down this path is simple inheritance, mostly because the user is only trying to implement 2 or 3 unique jobs. I feel as though this is just the easy answer that ends up causing a lot more headaches in the long run when you have lots of different jobs to implement.

So my main question is, what design patterns would someone use when there are a lot of different jobs that the programmer needs to implement?


texts: assigning values to shader parameters in the XNA content pipeline

texts:
I have tried creating a simple content processor that assigns the custom effect I created to models instead of the default BasicEffect.

[ContentProcessor(DisplayName = "Shadow Mapping Model")]
public class ShadowMappingModelProcessor : ModelProcessor
{
    protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
    {
        EffectMaterialContent shadowMappingMaterial = new EffectMaterialContent();
        shadowMappingMaterial.Effect = new ExternalReference<EffectContent>("Effects/MultipassShadowMapping.fx");
        return context.Convert<MaterialContent, MaterialContent>(shadowMappingMaterial, typeof(MaterialProcessor).Name);
    }
}

This works, but when I go to draw a model in a game, the effect has no material properties assigned.  How would I go about assigning, say, my DiffuseColor or SpecularColor shader parameter to white or (better) can I assign it to some value specified by the artist in the model?  (I think this may have something to do with the OpaqueDataDictionary but I am confused on how to use it--the content pipeline has always been a black box to me.)


texts: Stormy water like Temple Run 2 for Mobile

texts:
How can I make stormy water like they did in Temple Run 2. I've tried with Unity Water Pro to achieve the same result but when I include it in the project the frame rate crashes to 3 frames per second.

Unity Water basic doesn't fulfill the requirements at all. So is there any other way?


texts: C# XNA Making a TextBox Appear to input the X and Y coordinates

texts:
Okay I'm trying to find a way to not have to hard code in my values for the x and y coordinates. so far I have hard coded these in when you press certain numbers on num-pad it'll move the camera to that area.

        if(Keyboard.GetState().IsKeyDown(Keys.NumPad1))
        {
            x = 100;
                y = 100;
            spritePosition = new Vector2(x,y);
        }
        if (Keyboard.GetState().IsKeyDown(Keys.NumPad2))
        {
            x = 200;
            y = 200;
            spritePosition = new Vector2(x, y);
        }
        if (Keyboard.GetState().IsKeyDown(Keys.NumPad3))
        {
            x = 300;
            y = 300;
            spritePosition = new Vector2(x, y);
        }

What I'm trying to accomplish is to make a textbox or to be able to input x and y coordinates whilst the application is running

        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
        {
            x = 100;
            y = 100;
            spritePosition = new Vector2(x, y);
        }

so have something like this but allow the user to change the coordinate values whilst the application is running, when the user presses Enter, of course Console.WriteLine and Readline do not work, so I was wondering how to implement this sort of changes to make it work.


texts: Unity - Hide GameObject that is behind UI

texts:
I have the following example:

How can I prevent the part of the sprite that is highlighted in red and is behind the UI from being displayed on the camera, but having the background image still showing?


texts: How do I compute the angle between a pixel on an irregular curve and a circle colliding with it?

texts:
I'm building a custom physics engine to accompany a level-editor. This image shows how the level-editor outputs levels:

Now, some explanation is in order. The curve is defined by the red points. After they are connected in threes by circles (yellow lines show these circles), a system connects them in a 'streamlined' way - as shown by the blue lines. This makes the curves flow seamlessly.

Now, these curves are 'irregular,' so to say. For the accompanying physics engine - how do I detect the angle made between a pixel on the curve and a colliding circle (per-pixel collision check)?


texts:
Using Eclipse, I'm trying to write a simple hello world program in processing that simply draws a rectangle on the screen then has gravity drop it as seen in this tutorial.

The problem is that when I try to import the p5 package, it's not resolving so I can't declare my physics object.  I tried two things.

Download the zip, unzip it, then import the 3 jars (library, serialization, & testbed)

a. import org.jbox2d.p5.*; doesn't resolve but the others do

b. Physics physics; doesn't resolve
Download the older standalone testbed jar then import it

a. Physics physics; doesn't resolve;

Here is basically where I'm starting

import org.jbox2d.util.nonconvex.*;
import org.jbox2d.dynamics.contacts.*;
import org.jbox2d.testbed.*;
import org.jbox2d.collision.*;
import org.jbox2d.common.*;
import org.jbox2d.dynamics.joints.*;
import org.jbox2d.p5.*;
import org.jbox2d.dynamics.*;

import processing.core.PApplet;

public class MyFirstJBox2d extends PApplet  {

    Physics physics;

    public void setup() {
      size(640,480);
      frameRate(60);
      initScene();
    }

    public void draw() {
      background(0);

      if (keyPressed) {
        //Reset everything
        physics.destroy();
        initScene();
      }

    }

    public void initScene() {
      physics = new Physics(this, width, height);
      physics.setDensity(1.0f);
      physics.createRect(300,200,340,300);
    }
}


texts: XNA C# Platformer - physics engine or tile based?

texts:
I would like to get some opinions on whether I should develop my game using a physics engine (Farseer Physics seems to be the best option) or follow the traditional tile-based method.
Quick background:

It's a college project, my first game, but have 4 years academic programming experience
I just want a basic platformer with a few levels, nothing fancy
I want a shooting mechanic, run and gun, just like contra or metal slug for example
Possibly some simple puzzles

I have made a basic prototype with Farseer, the level is hardcoded with collisions and not really tiled, more like big full-screen sized tiles, with collision bodies drawn manually along the ground and walls etc. My main problem is I want a simple retro feel to the jumping and physics, but because it's a physics simulation engine, it's going to be realistic, whereas typical in air controllable physics for platformers aren't realistic. I have to make a box with wheel body fixture under it to have this effect, and it's glitchy and doesn't feel right.
I chose to use a physics engine because I tried the tile method initially and found it very hard to understand. The engine took care of a lot things to save me time. Being able to do slopes easily was nice, as was the freedom to draw collision bounds wherever I liked, rather then be restricted to a grid. This also gave me more freedom for art design.
In conclusion, I don't know which method to pick. I want to implement this in the most straightforward way, so it won't give me a headache later on. Preferably, a method which has an abundance of tutorials and resources so I don't get "stuck" doing something which has been done a million times before!