Wednesday, August 31, 2016

grammar - It has more to do with that I am lazy than that I am tired


Are all these sentences below correct and interchangeable?



1) It has more to do with that I am lazy than that I am tired.



2) It has more to do with the fact that I am lazy than that I am tired.


3) It has more to do with the fact that I am lazy than the fact that I am tired.


4) It has more to do with that I am lazy rather than that I am tired.


5) It has more to do with the fact that I am lazy rather than that I am tired.


6) It has more to do with the fact that I am lazy rather than the fact that I am tired.



(4. 5. and the 6. sentences are the same as the first three sentences except that I changed "than" to "rather than")


One more question: Are these sentences correct and interchangeable?



7) It has to do with the fact that I am lazy rather than that I am tired.



8) It has to do with that I am lazy rather than that I am tired.



My opinion on these eight sentences: I guess I have to use the phrase "the fact that" after the word "with", but I think I can use the word "that" after "than", and I guess it is better to use "that" after "than" or "rather than" instead of using "the fact that". Also I think "rather than" and "than" are interchangeable in the first six sentences I gave. What do you think?




american english - Does `That's very sweet of you` in the US sound like `That's very sweef you`?


Does That's very sweet of you in the US sound like That's very sweef you?
the of is only speak f and link with swee



Answer



I believe what you are hearing is just an example of "connected speech". When anyone speaks in their native language they do not stop after each word, but one word naturally runs into the next. To a British English speaker like myself, many American pronunciations of the letter 'T' sound more like a 'D'. As it is easier for a 'D' sound to merge with the 'F' sound in "of", you are probably noticing this more with American accents that with British.


sentence construction - The usage of "to get to do something"


Could you explain what the highlighted parts mean please?



An added benefit of Valerie's schedule is that it corresponds closely to her 13-year-old daughter's schedule, which means they have more time to spend together. "I love that I get to see her first thing in the morning, and make breakfast for her," Valerie says. She also hopes that her good sleep habits will rub off on her daughter, and that she will grow up with a healthy appreciation of sleep and its importance. "I certainly don't take sleep for granted like I used to."




If " to get to do something" means "to begin to do something" , can we use it in both forms :


For example :



I love that I get to see her first thing in the morning


I love that I get to seeing her first thing in the morning



Because a source says it should be used ing form after get to



get to doing something to start doing something



He got to thinking that it was all his fault.




Answer



The phrase "get to do something" implies to have the opportunity to do something. So the meaning of the first sentence is "I love to have the opportunity to see her first thing in the morning".


The phrases "get to do something and get to doing something" aren't interchangeable to convey the same meaning. The latter phrase means "to start doing something such as I got to talking to her. I got to thinking that it was his fault.


Both the sentences are grammatically correct, but they convey different senses.


Cave lighting in Unity


I have a cave that is inside a mountain (one mesh) that I created in Blender. I would like to make the cave quite dark inside so that either the player can light it up, or it is lit up with things such as crystals. Because I have ambient light through the scene, it's proven to be quite awkward to make it dark, and removing the ambient light kinda destroys the look.



I then played around with having a separate material for inside the cave so that I can make it darker, which kinda worked, but then I noticed a big issue with shadows.


The following images is from inside the cave far from the entrance.


The first image is with the default settings for shadow distance (in this case it was 70 in the quality settings). As you can see in the image, the shadow doesn't fill the cave because of the distance.


Default


Second image is with the shadow distance turned up to make sure the cave is in darkness (not pitch black though, due to ambient lighting), this took the setting from 70 to around 500.


Increased


The problem with setting the distance so high, is that it causes artifacts on geometry outside the cave, which look nasty.



What's the best way to make a cave dark (doesn't need to be pitch black) without removing ambient lighting for the whole scene?


I was looking at similar art styles to what I am working on, and Grow Home (Unity) is basically where I am heading. They have caves which would be acceptable for what I need, but am not sure how they done it. As far as I know, they have dynamic lighting, as I believe there is a day / night cycle, so I don't think anything is baked.





Answer



Some information on the Grow Home/Grow Up art direction here if you're still interested :)


We relied very heavily on our custom Fresnel shader for... well... the entire look of the game. But it was especially important for the lighting of cave interiors. We pretty much only had one directional light in the whole game from the sun, but you're not seeing any of that here. The 'lighting' that you see in the screenshot above all comes from the Fresnel effect, which reflects the colour of the sky dome on all acute angled polys, giving you that rim-lighting effect everywhere you look.


grammaticality - ran lower to the ground vs ran low to the ground


Can you explain to me why author have used word "lower" instead of "low". The text is:



I was too far away to see anyone, so I parked behind a big rock at the base of the mountain, left my helmet there, and hurried into the tall grass. The trees were about 200 yards away when I ducked and ran lower to the ground.



Is that correct to tell "ran lower to the ground"?.




Tuesday, August 30, 2016

How should I represent a tile in OpenGL-es


Let me start with I am currently learning OpenGl-es using Android.


I have been having the hardest time trying to design a simple and logical way of making tiles (2d flat polygons). The tutorials tell me to just keep the polygon as a float array of veticies:


private float vertices[] = {
-1.0f, 1.0f, 0.0f, // 0, Top Left
-1.0f, -1.0f, 0.0f, // 1, Bottom Left
1.0f, -1.0f, 0.0f, // 2, Bottom Right
1.0f, 1.0f, 0.0f, // 3, Top Right

};

That in and of itself is easy enough. I modified the code to suit my desired polygon and it drew fantastic. Now I wanted to draw more tiles and have a scrolling feature (look around the world). But I'm not sure what's the best way to do so.


Should I leave every tile with a float array of indices and when it comes time to move the tile, directly modify thefloat values?


Is it a good idea to create an ArrayOfPoints (Point just being a container for exactly 3 float values) class to hold all of the points and then have methods that cycle through the points and change their values in a more safe fashion?


Does anyone have any tutorials on simple tile based map building so I can look at how they do their maps?


(Note: these questions are based on what I have read on animating. That is to say that you change the coordinates of the object in relation to the origin and leave the camera at 0,0,0. If it is more proper to just leave objects where they are, I guess my question loses value.)



Answer



I've tried lots of variations myself; the recipe I've found best is:


Put any tile textures into a texture atlas. In this way, you can draw your whole map in a single draw-op because they are all using the same texture.



Mipmap the texture atlas, natuarally. For a large number of tiles you may spill over one texture 'page' in the atlas and it turns into multiple pages. If you keep that in mind, it won't be a big deal to retrofit support for pages if you need it.


If your tiles are a nice fixed size then just use the smallest non-float data-type for the vertex components for the points that you can e.g. bytes if the map is less than 256x256. Texture coordinates also help not being float.


Now build your map VBO using interleaved texture coordinates and vertices for a GL_TRIANGLE_STRIP array. I imagine that each vertex data starting on a nice 4-byte boundary is a good idea, but I have no empirical data to support that. Its just a hunch. Avoid element index arrays.


It depends on the camera position and such, but I found the best performance is to regenerate the tile array to draw all visible tiles each time the camera moves! This has, in my code, won more framerate than approaches of keeping all vertices GPU-side in blocks or such and issuing multiple calls to draw all the bits that are visible.


So what I normally do is, if the camera moves, compute the visible tiles and make an array of them, that I draw. Then if the next frame the camera hasn't moved, at that point promote it to be the vbo for subsequent frames until the camera moves again.


You could use gl_VertexID in the vertex shader to avoid needing x and z components for your vertices at all. (I haven't tried that, I've had problems with gl_VertexID on integrated Intel drivers on the desktop, stopping my cross-platform efforts in that direction. But on Android (Imagination/NVidia/Mali) devices it likely works well and is well worth the effort.)


If your map has varying heights then you have to have three components (or, with gl_VertexID, one) for the vertices but otherwise you don't need that y and then you don't need to track the normals per vertex either.


I rather hope someone weighs in with sounder advice to try something I haven't thought of myself, so as to improve my engine too ;)


Drawing large 2D sidescroller level terrain


I'm a relatively good programmer but now that it comes to add some basic levels to my 2D game I'm kinda stuck.


What I want to do: An acceptable, large (8000 * 1000 pixels) "green hills" test level for my game.



  • What is the best way for me to do this?



It doesn't have to look great, it just shouldn't look like it was made in MS paint with the line and paint bucket tool.


Basically it should just mud with grass on top of it, shaped in some form of hills.


But how should I draw it, I can't just take out the pencil tool and start drawing it pixel per pixel, can I?



Answer



Photoshop has layer-effects which can be used to draw good looking levels really fast. I don't know if that would work with GIMP, but here are some steps how to get something on screen fast using Photoshop:


Instructions



  1. Get some dirt and grass textures. The one I'm using in my example are from this freetexture set.

  2. Open a dirt texture in Photoshop. Select all Ctrl-A and copy Ctrl-C. Then select Edit > Define Pattern... from the Menu. Name your Pattern "Dirt".


  3. Do the same for the Grass texture, name it "Grass".

  4. Create a new Layer in Photoshop and apply the Pattern Overlay and Stroke Effect to your layer. Select the "Dirt" pattern for the overlay and the "Grass" pattern for your Stroke (see images below).

  5. Paint with any brush on your layer... instead of having a boring single color, it should render as a landscape, thanks to the layer effects. The beauty of this is, that you can freely add/remove parts of your landscape by using regular drawing tools like the brush or eraser.

  6. (optional) Draw a gradient from dark blue (top) to light blue (bottom) on the background layer for your sky (you could also use layer-effects for that).

  7. (optional) Add some more layer-effects like a gradient and drop-shadow to your "landscape" layer in order to achieve a better look.


Images


Pattern Overlay settings


Photoshop pattern overlay settings


Stroke settings



Photoshop stroke settings


Final result


With some more layer effects and a background.


final image


You can also download the PSD file here to have a look at it.


c# - save a particular area of the scene as screenshot in unity


I need to save a particular part of the scene as screenshot. I have done a sample to show the particular part of the scene.



When I click on the rectangular area the selected area will being shown on the screen on a texture (marked in red rectangle):



But when I save, the whole scene is getting saved but not the selected part:




Here is code:


Texture2D screencap;
Texture2D border;
bool shot=false;
public string path;

void Start () {
screencap=new Texture2D(300,200,TextureFormat.RGB24,false);
border=new Texture2D(2,2,TextureFormat.ARGB32,false);

border.Apply();
}

// Update is called once per frame
void Update () {
if(Input.GetKeyUp(KeyCode.Mouse0))
{
StartCoroutine("Capture");
}


}
string fileName(int width, int height)
{
return string.Format("screen_{0}x{1}_{2}.png",
width, height,
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}

void OnGUI()
{

GUI.DrawTexture(new Rect(200,100,300,2),border,ScaleMode.StretchToFill);
GUI.DrawTexture(new Rect(200,300,300,2),border,ScaleMode.StretchToFill);
GUI.DrawTexture(new Rect(195,100,2,200),border,ScaleMode.StretchToFill);
GUI.DrawTexture(new Rect(500,100,2,201),border,ScaleMode.StretchToFill);

if(shot)
{
GUI.DrawTexture(new Rect(50,10,60,40),screencap,ScaleMode.StretchToFill);
//Application.CaptureScreenshot(myFolderLocation+myFilename);
}

}

IEnumerator Capture()
{
yield return new WaitForEndOfFrame();
screencap.ReadPixels(new Rect(198,98,298,198),0,0);
screencap.Apply();
shot=true;

byte[] bytes=border.EncodeToPNG();

string filename=fileName(Convert.ToInt32(screencap.width), Convert.ToInt32(screencap.height));
Application.CaptureScreenshot("D:"+filename);
}

How can I save only the particular part in unity,can anybody please help me out.



Answer



Your


Application.CaptureScreenshot("D:"+filename);

saves the whole shene on file, you need to save the texture2d to file



Follow the example:


 import System.IO;

function SaveTextureToFile( texture: Texture2D,fileName)
{
var bytes=texture.EncodeToPNG();
var file = new File.Open(Application.dataPath + "/"+fileName,FileMode.Create);
var binary= new BinaryWriter(file);
binary.Write(bytes);
file.Close();

}

Call it using:


      SaveTextureToFile( screencap,"picture.png");

EDIT: a variation of SaveTextureToFile can be:


     function SaveTextureToFile(  Texture2D texture ,string fileName)
{
byte[] bytes = texture.EncodeToPNG();
File.WriteAllBytes(filename, bytes);

}

xna - How is 2D lighting implemented?


I am wondering what the best way to approach a "lighting" effect in 2D games is. For instance, if my main character is glowing, what techniques can I use to complete the visual effect of the character glowing when it is near other objects which would be affected by the light?



Answer



You could overlay a simple glow effect texture with soft transparent edges. If you want lighting/shadows similar to what you may find in a 3d world you could do something like this: http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/. However, if you are new to HLSL, then that may be a little bit too much.


edit: I stumbled onto a nice HTML5 2d light tutorial


Monday, August 29, 2016

physics - How to account for speed of the vehicle when shooting shells from it?


I'm developing a simple 3D ship game using libgdx and bullet.



When a user taps the mouse I create a new shell object and send it in the direction of the mouse click. However, if the user has tapped the mouse in the direction where the ship is currently moving, the ship catches up to the shells very quickly and can sometimes even get hit by them - simply because the speed of shells and the ship are quite comparable.


I think I need to account for ship speed when generating the initial impulse for the shells, and I tried doing that (see "new line added"), but I cannot figure out if what I'm doing is the proper way and if yes, how to calculate the correct coefficient.


public void createShell(Vector3 origin, Vector3 direction, Vector3 platformVelocity, float velocity) {
long shellId = System.currentTimeMillis(); // hack
ShellState state = getState().createShellState(shellId, origin.x, origin.y, origin.z);
ShellEntity entity = EntityFactory.getInstance().createShellEntity(shellId, state);

add(entity);
entity.getBody().applyCentralImpulse(platformVelocity.mul(velocity * 0.02f)); // new line added, to compensate for the moving platform, no idea how to calculate proper coefficient
entity.getBody().applyCentralImpulse(direction.nor().mul(velocity));

}

private final Vector3 v3 = new Vector3();
public void shootGun(Vector3 direction) {
Vector3 shipVelocity = world.getShipEntities().get(id).getBody().getLinearVelocity();
world.getState().getShipStates().get(id).transform.getTranslation(v3); // current location of our ship
v3.add(direction.nor().mul(10.0f)); // hack; this is to avoid shell immediately impacting the ship that it got shot out from
world.createShell(v3, direction, shipVelocity, 500);
}


Edit - I switched to:


    v3.set(direction);
v3.nor().mul(velocity);

if (platformVelocity != null)
v3.add(platformVelocity);

entity.getBody().setLinearVelocity(v3);

And it seems to work (so adding the velocities and setting them on the body).



However, I'm not sure what the drawbacks are and why the tutorial application used impulses instead of setting velocities.


I also think that while this is physically correct it leads to strange results (gun range is two times further when shooting forward than when shooting sideways).


The root cause is because really the shells are indeed too slow, but I like them slow as otherwise the gameplay is too fast-paced, and they travel too far.


I think I need some compromise between physics-realistic and ignore-platform-velocity.



Answer



The shell's speed was the same as the ship's speed before it got fired, if you think about it. It was sitting on the ship. So, if you add the velocity from being fired to the velocity of the ship, you should get the correct result.


plural forms - Time expression plus has/have




Ten minutes have passed. Let's wait five more.




Is using have here correct?




c# - What are the steps to instantiate a button in Unity?


Given a Canvas test_canvas containing a Button test_button and an empty GameObject that manages instantiation and scripts and the like called test_manager, what are the steps to instantiate this button through code as opposed to having it already there?


I've tried making the button a prefab and instantiating it as I would any other object but that didn't work. I tried making the canvas a prefab and then trying the button but nothing. I've searched around for quite some time and there's mention of RectTransform and SetParent but steps or specific details would clear up my confusion



Answer



Prefab your Canvas and a Button and add this script to the test_manager gameobject


using UnityEngine;

using System.Collections;
using UnityEngine.UI;

public class TestManagerScript : MonoBehaviour {
public GameObject canvas;
public GameObject button;

void Start () {
GameObject newButton = Instantiate(button) as GameObject;
newButton.transform.SetParent(newCanvas.transform, false);

}
}

be sure to drag the prefab button and prefab canvas to the public field slots this creates on the test_manager gameobject.


If you are also Instantiating the canvas you want to keep in mind that the UI will display from top to bottom as it is listed in the hierarchy. So you would want something like this.


 void Start () {

GameObject newCanvas = Instantiate(canvas) as GameObject;
GameObject newButton = Instantiate(button) as GameObject;
newButton.transform.SetParent(newCanvas.transform, false);

}

phrase request - Possible responses to "thank you"


Is "you are welcome" more polite than "no problem"?


What is the general proper reply to a thank-you?



Answer



First of all, this is always contracted "You're welcome" and is THE best response to thanks in any situation (NOT: you are, which would sound robotic)


No problem is quite familiar and not as "social" as you're welcome. An even more familiar version of this is no sweat.



Don't mention it is quite appropriate instead of you're welcome. If you went to significant trouble and someone thanks you, you can also respond with No trouble at all or my pleasure.


meaning - Present Simple vs Present Progressive


What is the difference in meaning between the following two sentences?



(1) I am completely honest with you right now.


(2) I am being completely honest with you right now.




Answer



Verbs like be and know and see, which express a state are far less likely to be cast in the progressive than verbs which express an action or event. The primary effect of the progressive construction is to "recategorize" an event or action as a continuing state, so its use with stative verbs is superfluous.


When stative verbs are cast in the progressive it usually signals one of two things: either the "state" is regarded as temporary and likely to end soon, or the verb has been recategorized semantically: it has a different sense in the progressive.


In the case of be, both these changes take place with the progressive: be is understood in the sense behave, and the behavior expressed is understood to be temporary rather than a permanent characteristic. For instance,




Brian is a jerk means that Brian is always a jerk, but
Brian is being a jerk means that right now Brian is behaving like a jerk.



So it is one thing to say I am completely honest with you—this is the ordinary stative use of be and implies that I am always completely honest with you. It is a permanent aspect of my character. But I am completely honest with you right now is odd and jarring, because bare am and right now imply two different time scopes.


But saying I am being completely honest with you right now is idiomatic. This says that even if I may not always be completely honest with you or with other people, what I am saying and doing right now—my current behavior—is in fact completely honest.




And in fact the only reason I would say this would be if you gave some indication that you believed I was not being honest with you.


sentence construction - Using the continuous or the infinitive form of a verb when is used as a noun/complement


I believe the following to be wrong:


"I don't commit enough to learn English"


Surely the continuous form is correct:


"I don't commit enough to learning English"


Or, maybe even better:


"I don't commit enough to the learning of English"


But I am unsure of what rules are determining the above use, because I believe we can have the following:


"I don't like to eat raw fish"



In this phrase the use of the infinitive form "to eat" seems to work fine.


Is it that some verbs are not usable in the infinitive form?




Sunday, August 28, 2016

Sprite draw-order in libgdx


From other frameworks I know methods for easy ordering sprites within a spritebatch (to determine if a sprite has to be drawn in front or behind another sprite). For example in MonoGame/XNA this is called Sprite.depth or Pyglet has its OrderedGroups.



But I cannot find anything like that in libgdx. I've read that libgdx' scene2d has something like that but I don't want to use that as I use a entity system (ashley) and want to keep rendering separeted from the other logic.


What is the appropriate way to set the draw-order of libgdx sprites?



Answer



You are correct that libGDX doesn't contain any sort of built-in support for rendering sprites in a certain order. (If it's there, I haven't seen it, and I've been using libGDX for a number of years.)


What I do is create a SpriteComponent class that wraps the Texture object and emits x, y, and z attributes.


Then in my draw method, I sort all SpriteComponents by z (ascendingly) and draw them -- so lower-Z items draw first, then higher-Z items on top.


data structure - Where and how to store players collection in a computer card game?


I am developing a trading card game ( something like Hearthstone but not as complex) and I am faced with the following problem: I don't know what is the optimal way to store players collections and decks (the cards that they have available).



I thought of storing their collections on a local file on their device, but that seems bad, as they could probably modify that file and get themselves cards that they shouldn't have.


The second idea is that i could save all their decks and collection in a database. But having one table for each player isn't possible. Having one table with all that data something like PlayerCards(id, cardId, playerName, deckName) seems like it might work, but the table would be huge, and containg quite a bit of redundant data (cards that are in the same collection but are in multiple decks).


What would be the proper way to do it?



Answer



The relational-database-by-the-book solution would have a table players, a table cards_owned_by_players, a table decks a table cards_in_deck and a table cards.


Here is an entity-relationship diagram of the whole schema. If you are wondering where cards_in_deck and cards_owned_by_players went: note that an N:M relationship needs to be represented with a separate relation-table.


ERD diagram



  • A player owns m cards

  • A card is owned by n players


  • A player has n decks

  • A deck is always owned by one player

  • A deck has n cards

  • A card is in m decks


The table players would have the primary key playerId. It contains all the information about the player themselves (like the player name).


The table cards_owned_by_players manages the ownership relation of individual cards. Its primary key would be cardId and playerId. If a player can own more than one copy of a card, it would have a value-field count. To get all cards owned by a player, you can do SELECT cardId FROM cards_owned_by_players WHERE playerId = [id]. If you also need additional information about these cards, like their artwork or name, you would add a JOIN with cards to this query. More about the table cards later.


The table decks would have the primary key deckId. It includes all the information about the deck itself (name of the deck and the Id of the player who owns it).


The table cards would have the primary key cardId and include the information about the cards themselves (name, description, artwork, functionality). You have one entry per type of card. I.e. if you have a card "Goblin Warrior" which is owned by 1752125 players and is in 2357689 decks, you would still only have one row for it in cards.


The table cards_in_deck would have a compound primary key of deckId and cardId. If your game allows multiple copies of a card in one deck, the value field would be count. When it doesn't, that table might not actually need any fields at all except the primary key.



As an example query, let's say you want the deck names and card names of all cards in all decks by a specific player which you only know by name "Bob". You would then do the query:


SELECT decks.name, cards.name, cards_in_deck.count
FROM players
JOIN decks ON players.playerId = decks.playerId
JOIN cards_in_deck ON decks.deckId = cards_in_deck.deckId
JOIN cards ON cards_in_deck.cardId = cards.cardId
WHERE players.name = "Bob"

A JOIN over 4 tables looks like it could be a lot of work for the database, but notice that they are all JOINs on primary keys. Most database management systems optimize heavily for primary key access. The slowest parts of this query will likely be WHERE players.name = "Bob", because that will require a full table scan of the players table, unless you have an index on the name field.


Also, don't be afraid of your cards_in_deck table growing too large. We are living in the age of big data. Many database management systems are capable of handling tables with billions of rows and terabytes of data... as long as all queries on them are using primary key or index access.





An optimized solution:


If you ever meet the ghost of Edgar F. Codd, please don't tell him I wrote this.


If you are sure you will always query only for the complete content of a deck and never query for individual cards in a deck, you can remove the table cards_in_deck and instead serialize the deck content into a binary representation and put it into one BLOB field of the table deck. You will no longer be able to do queries like "all players which have card X in their deck". Also, making a change to a deck will now require to get the whole BLOB, deserialize it, change it, serialize it, and write it back. But it will be a lot faster to get the whole deck of a specific player.


You can now of course no longer do a JOIN with cards. But you might not have to do that. You won't have that many different cards (even Hearthstone only has about 2000), your game mechanics will constantly need them, and your card information will only change when you make a major update to your game. So it might be better to keep the card information constantly in the game server's memory instead of re-reading it from the database all the time.


Friday, August 26, 2016

modal verbs - "I will be loving you 'til we're 70" vs. "I will love you 'til we're 70"


From Ed Sheeran's song Thinking Out Loud:



And, darling, I will be loving you 'til we're 70



Why is it not



And, darling, I will love you 'til we're 70




?


Why is progressive used here?



Answer




From Ed Sheeran's song Thinking Out Loud:



And, darling, I will be loving you 'til we're 70



Why is it not




And, darling, I will love you 'til we're 70



Why is progressive used here?



I don't know why the author chose the progressive.


But the difference between the two is as follows:



I will love you until we're 70




Every reference to the future is somewhat of a prediction, because we are talking about things that haven't happened yet.


will + base infinitive is the most common way to refer to future time. The use of to will involves the speaker's volition.


The use of will here refers to the speaker's current resolve to carry through on a particular action. Here, the speaker is promising that he will love the person until they are 70.



I will be loving you until we are 70



Here, the reference is not to the speaker's volition. Rather, the subtle meaning is that the thing predicted will happen without the interference of anyone's volition. The predicted event will happen as a matter of course, not because someone is promising it will happen. There is a matter-of-fact attitude, as in 'Oh, by the way II'll be loving you until we're 70.'


There is a famous song called "She'll be coming 'round the mountain" which has the chorus



She'll be coming 'round the mountain when she comes




This is the same use of will be + present progressive. It refers to her coming around the mountain as something that will happen without the involvement or interference of anyone's will (volition). The predicted event will happen, and that is that. No reference to the subject's resolve or intention is made.


Another example:



I'll drive to New York Tuesday.



Here, this includes the speaker's will or volition. He's made a decision about the event and so his will is involved. Also the meaning expressed is that the speaker is referring to his current resolve to carry out the stated action.


By comparison,



I'll be driving to New York Tuesday.




does not really refer to the speaker's resolve, and it is not a promise; but merely a statement (prediction) of what will occur Tuesday.


So, if someone says



I'll be driving to New York Tuesday; why don't you ride with me?



The speaker is, again, mentioning the future as a matter of course. (No one has decided that I'm driving to New York Tuesday, it is just something that is going to happen.) Since the action of my driving to New York Tuesday is going to happen, my driving you to New York is no problem or trouble at all.




Note: this answer relies heaviliy on:


Leech, Geoffrey N. (2014-01-14). Meaning and the English Verb. Taylor and Francis.



c++ - What are some programming design patterns that are useful in game development?



I have a few books on Design Patterns, and have read some articles, but cannot intuitively figure out which programming design patterns would be useful in game development.


For example, I have a book called ActionScript 3 with Design Patterns that details several design patterns such as Model View Controller, Singleton, Factory, Command, etc.


As someone new to this, I cannot figure out which of these would be useful, or in fact if any of these are the design patterns I should be learning and trying to use. Perhaps there are other, more game-programming-specific design patterns that I am not even aware of?


If you have experience using a certain design pattern in game development, I'd love to hear it. Reasoning as to why it was used, code samples, or online resources would all be very helpful as well if you have them. I am at the moment most interested in ActionScript 3 and C++ implementations, but could definitely benefit from experience and examples from any language.


Thanks!



Answer




Now for a less flippant response, with some suggestions. Don't take these as implementation recommendations, more as examples of possible use.



  • Builder: set up component-based entity one component at a time, based on data

  • Factory Method: create NPCs or GUI widgets based on a string read from a file

  • Prototype: store one generic 'Elf' character with initial properties and create Elf instances by cloning it.

  • Singleton: this space deliberately left blank.

  • Adapter: incorporate an optional 3rd party library by wrapping it in a layer that looks like your existing code. Very useful with DLLs.

  • Composite: make a scene graph of renderable objects, or make a GUI out of a tree of Widgets

  • Facade: simplify complex 3rd party libraries by providing a simpler interface to make your life easier later.

  • Flyweight: store the shared aspects of an NPC (eg. models, textures, animations) separately from the individual aspects (eg. position, health) in a mostly transparent way


  • Proxy: Create small classes on a client that represent larger, more complex classes on a server, and forward requests via the network.

  • Chain of responsibility: handle input as a chain of handlers, eg. global keys (eg. for screen shots), then the GUI (eg. in case a text box is focused or a menu is up), then the game (eg. for moving a character)

  • Command: encapsulate game functionality as commands which can be typed into a console, stored and replayed, or even scripted to help test the game

  • Mediator: implement game entities as a small mediator class that operates on different components (eg. reading from the health component in order to pass the data to the AI component)

  • Observer: have the renderable representation of a character listen to events from the logical representation, in order to change the visual presentation when necessary without the game logic needing to know anything about rendering code

  • State: store NPC AI as one of several states, eg. Attacking, Wandering, Fleeing. Each can have its own update() method and whatever other data it needs (eg. storing which character it is attacking or fleeing from, the area in which it is wandering, etc.)

  • Strategy: switch between different heuristics for your A* search, depending on what sort of terrain you're in, or perhaps even to use the same A* framework to do both pathfinding and more generic planning

  • Template method: set up a generic 'combat' routine, with various hook functions to handle each step, eg. decrement ammo, calculate hit chance, resolve hit or miss, calculate damage, and each type of attack skill will implement the methods in their own specific way


Some patterns left out due to lack of inspiration.



Are there any open source or free 3D modelling/animation tools that are widely used by indie game developers?



I have tried out Blender and Milkshape 3D, but my question is mainly asking if there is any 3D animation/modelling software that is open source, free, or has an indie license available that is widely used by indie developers?



Answer



I really like Wikipedia's comparison articles; the Comparison of 3D computer graphics software article is particularly relevant to this question.


In particular, you may want to check out the discontinued Caligari trueSpace which was used in game modeling IIRC, or Ayam, "a free 3D modelling environment for the RenderMan interface."


But Blender, by far, is the most widely used free 3D software, and I do believe your second choice, Milkshape, would probably be the second most popular. I enjoy Milkshape myself because of the ease of implementation of the MS3D format.


Thursday, August 25, 2016

unity - Merging box colliders for optimization


Look at the picture.


The figure on the left shows the individual box colliders in green.


The yellow boxes on the right are the results of the optimization of the original box colliders.


What is the algorithm that makes this possible?


enter image description here




aspect - What tense is this? 'Despite their already having paid the money...'


I was reading a piece of writing recently and I came across a very strangely phrased sentence that took me a while to understand. Can anyone identify the sentence's tense or really just what makes it so strange?



Despite their already having paid the money, there was an additional tax.




Answer



despite is a preposition meaning not prevented by. A preposition normally attaches a noun to a sentence, for example:




He completed the marathon, despite his age.



already having paid the money is a noun phrase. We can include a verb in a noun phrase using either a gerund or an infinitive: in this case, a gerund is used. We make the present form of a gerund by putting -ing on the end of the verb- this is quite common- but we can also make the past gerund form by putting having in front of the perfect form- thus, having paid.


The main verb in the sentence is was, which is past simple. The strange bit in this sentence is the perfect form of the gerund, having paid.


There are fewer opportunities to use the past form of a gerund than the present form, and in addition, according to this NGram, its usage has declined steadily over the past 200 years.


Wednesday, August 24, 2016

game mechanics - Moving from A(x,y) to B(x1,y1) with constant speed?


I currently have something like:


float deltaX = point0.getX() - point1.getX();
float deltaY = point0.getY() - point1.getY();

And every 0.01 seconds I refresh my objects position like this:


object.setPosition(object.getX()-deltaX/100,object.getY()-deltaY/100);

So this moves my object from point0 to point1 in 1 second. What I need is having the 2 points, to be able to move the object from point0 ,facing(in the direction of) point1 with a constant speed. Thus, when I have a point closer to my initial point the object will move towards it with the same speed it does if I would have a farther point. Any suggestions are appreciated. Thanks.



Answer




I'll use some linear algebra structures since it's easier to describe the operations that way. In case you don't know how to implement these vector operations I'll give a quick explanation at the end.


So let's say you start with these values: startand end mark the end points of the movement, speed is how many pixels it should move by second, and elapsed is the rate at which you'll update your object's position (some engines already provide that value for you):


Vector2 start = new Vector2(x1, y2);
Vector2 end = new Vector2(x2, y2);
float speed = 100;
float elapsed = 0.01f;

The first thing you'll want to calculate is the distance between both points, and a normalized vector containing the direction from start to end. Also, you should "snap" the object position to the start point. This step is done only once, at the beginning:


float distance = Vector2.Distance(start, end);
Vector2 direction = Vector2.Normalize(end - start);

object.Position = start;
moving = true;

Then on your update method, you move the object by adding a multiplication of direction, speed and elapsed to its position. After that, to check if the movement is over, you see if the distance between the start point and the object's current position is greater than the initial distance you calculated. If that's true, we snap the object's position to the end point, and stop moving the object:


if(moving == true)
{
object.Position += direction * speed * elapsed;
if(Vector2.Distance(start, object.Position) >= distance)
{
object.Position = end;

moving = false;
}
}



Quick Vector Operations Reference


Representation


Vector2 A = float aX, aY;

Sum / Subtract



A+B = a.x + b.x; a.y + b.y;
A-B = a.x - b.x; a.y - b.y;

Multiply by Scalar (float)


A*float = a.x*float; a.y*float;

Length / Distance


length(A) = sqrt(a.x*a.x + a.y*a.y)
distance(A,B) = length(B-A)


Normalize


normalize(A) = a.X/length(A); a.Y/length(A);

That should be enough to convert the above code into regular operations if you don't have a Vector class available to you.




Example of Conversion


// Your Variables
float startX, startY, endX, endY;
float speed = 100;
float elapsed = 0.01f;


// On starting movement
float distance = Math.sqrt(Math.pow(endX-startX,2)+Math.pow(endY-startY,2));
float directionX = (endX-startX) / distance;
float directionY = (endY-startY) / distance;
object.X = startX;
object.Y = startY;
moving = true;

// On update

if(moving == true)
{
object.X += directionX * speed * elapsed;
object.Y += directionY * speed * elapsed;
if(Math.sqrt(Math.pow(object.X-startX,2)+Math.pow(object.Y-startY,2)) >= distance)
{
object.X = endX;
object.Y = endY;
moving = false;
}

}

grid - Why don't we use octogonal maps instead of hexagonal maps?


I understand the advantage of hexagonal tiles over square ones. But why aren't octagons used instead? I would think they would provide better, more natural movement in eight directions.


I was thinking about using that kind of map in some game, but I haven't seen any games using it, so I wonder if I missed something obviously flawed about using it?



Answer



Octogons:


enter image description here


Hexagons:


enter image description here



The gaps in the octogons make for an unappealing game world.


Typically, if you wanted to allow for eight directions of movement, you would just use squares.


3d - Why / how does XNA's right-handed coordinate system effect anything if you can specify near/far Z values?


I am told repeatedly that XNA Game Studio uses a right-handed coordinate system, and I understand the difference between a right-handed and left-handed coordinate system. But given that you can use a method like Matrix.CreateOrthographicOffCenter to create your own custom projection matrix, specifying the left, right, top, bottom, zNear and zFar values, when does XNA's coordinate system come into play?


For example, I'm told that in a right-handed coordinate system, increasingly negative Z values go "into" the screen. But I can easily create my projection matrix like this:


Matrix.CreateOrthographicOffCenter(left, right, bottom, top, 0.1f, 10000f);


I've now specified a lower value for the near Z than the far Z, which, as I understand it, means that positive Z now goes into the screen. I can similarly tweak the values of left/right/top/bottom to achieve similar results.


If specifying a lower zNear than zFar value doesn't affect the Z direction of the coordinate system, what does it do? And when is the right-handed coordinate system enforced?


The reason I ask is that I'm trying to implement a 2.5D camera that supports zooming and rotation, and I've spent two full days encountering one unexpected result after another.




Answer



Okay, a couple of questions here, so I'll do my best to explain them all.


Coordinate System


The coordinate system of anything affects more than just the orthographic projection. It affects translation and rotation as well.


For example, set up your camera projection as you have described. Now create an object and set it to move either toward you or away from you. It will move toward the camera when you increase the Z-value of the object's coordinate and move away from the camera when you decrease the Z-value.


Now if you rotate your camera around the scene (for gameplay reasons, or whatever you like) then the world's Z-axis stays the same, so this time increasing or decreasing the Z-value will affect the object in a different way (depending on the orientation of your camera.


Rotation


Now for rotation:


Rotating around the X, Y and Z axis is slightly different in right-hand systems than left-hand systems.


I refer you to this picture:



alt text


The left image shows rotations in a left-handed system and the right shows rotations in a right-handed system (although not very well, but it was the only picture I could find relatively quickly from Wikipedia)


The easiest way to explain it is using your hands. If you put up your right hand when your thumb and index finger make an L-shape with your palm facing towards you, your thumb is the positive X direction and your index finger is the positive Y direction.


Now bend your middle finger so it is point towards you, this is the positive Z direction in a right handed system (I'm getting to rotations, honest! Just wanted to make everything clear)


Make a thumbs up and point your thumb towards your face. The direction in which your fingers coil is the POSITIVE direction for a rotation about the Z-axis.


So lets add +45 degrees of rotation to the Z axis on the object and it will dip its left side down and its right side up.


Phew, hope that explains rotations in a right-handed system.


Projection


Now to answer your projection matrix questions. No, creating a projection does not change the world's Z-axis. All it does is is creates a view frustum (Best explained here: Viewing Frustum)


To work with this rule enforcement, it might be best to have LOCAL axes for your world objects (including your camera).



I usually have Heading, Right and Up normalized vector members for each of my world objects to help me out in this respect. So whenever you translate an object, instead of adding X, Y or Z values, I simply map it relative to the vectors (e.g. If I press forward, then my camera moves towards it heading, if I press right, it moves when its right vector is pointing).


Zoom


I know you didn't ask about zooming, but I thought I'd nip it in the bud since you want your camera to support it too.


Personally, I do a cheap zooming effect by changing the FieldOfView member of the view frustum. This is usually set to around 45-60 degrees. Play around with this until you get the effect you want.


I think that's everything, hope it helps! :)


Why is spacebar causing Unity to fire last OnClick() event



I have a turn based roguelike with input issues that are driving me nuts.


I use the Unity Input/GetAxis() for keyboard input. I recently added a skill bar with clickable buttons that pass an int parameter to a simple class when clicked.


The problem I am having is that the OnClick() event, on the last button that was clicked, fires whenever the SPACE bar is pressed.


What could cause this? I do not have space set on any of the input Axes (I did originally and both the axes attached to SPACE and the OnClick() would fire)


Edit: The code is below. It is called by the OnClick() handler on the button in the inspector. If you run the project and press SPACE nothing happens. Then if you click a button the Debug.Log fires. Then press SPACE again and the debug fires again with the same button number as was last clicked.


public class SkillClickNotifier : MonoBehaviour
{
[HideInInspector]
public int SkillClicked;


public void ButtonClicked(int skill)
{
Debug.Log("Button Clicked: "+ skill);
// SkillClicked = skill;
// GameManager.Notifications.PostNotification(this, "SkillClicked");
}
}


questions - Position of 'not' in a negative interrogative?


Source: Carlill v Carbolic Smoke Ball Company [1892], judgement of Lindley LJ



But there is another view. Does not the person who acts upon this advertisement and accepts the offer ♦ put himself to some inconvenience at the request of the defendants? Is it nothing to use this ball three times daily for two weeks according to the directions at the request of the advertiser? Is that to go for nothing?



I tried ELU. Am I right that this is a negative interrogative, and that Lindley LJ is just asking rhetorically: 'Does not the person .... put himself to some inconvenience ...'?



Why or why not should not be situated where I have inserted ♦ (ie the lozenge)? What differs?


PS: This Reddit post explicates this older syntax.



Answer



The key here is Heavy Noun Phrase Shift. Here's how it works:




  1. First, let's start with the canonical (declarative, affirmative) version:



    [The person who acts upon this advertisement and accepts the offer]subject puts himself to some inconvenience at the request of the defendants.






  2. Then we'll add the dummy auxiliary do. We need this auxiliary for two reasons: to negate the predicate, and to mark the clause as interrogative through inversion:



    [The person who acts upon this advertisement and accepts the offer]subject doesauxiliary put himself to some inconvenience at the request of the defendants.





  3. At this point, we can negate the predicate:




    [The person who acts upon this advertisement and accepts the offer]subject doesauxiliary notnegator put himself to some inconvenience at the request of the defendants.





  4. And now we can invert the subject and auxiliary, turning our declarative clause into an interrogative clause:



    Doesauxiliary [the person who acts upon this advertisement and accepts the offer]subject notnegator put himself to some inconvenience at the request of the defendants?






  5. Last, because our subject is so long and syntactical complex, and because this is particularly formal English, we can optionally make use of the rare Heavy Noun Phrase Shift, pushing our subject to the right out of its basic position, past the negator:



    Doesauxiliary notnegator [the person who acts upon this advertisement and accepts the offer]subject put himself to some inconvenience at the request of the defendants?





When these conditions aren't met, we can't shift the subject noun phrase to the right:



Doesauxiliary shesubject notnegator like ice cream?


*Doesauxiliary notnegator shesubject like ice cream? (ungrammatical)




The subject she isn't long or syntactically complex enough to count as as a "heavy" noun phrase, so it can't be shifted past the negator.


In contrast, the contracted form doesn't doesn't involve Heavy NP Shift; -n't is a suffix, and so doesn't is a single word which inverts with a subject without any of these restrictions:



Shesubject doesn'tnegated-auxiliary like ice cream.


Doesn'tnegated-auxiliary shesubject like ice cream?



For more discussion, see my previous answer.


Is it legal to sell or monetize games created with the Unity 3D free edition?


Is it okay to use Unity 3D programming and gaming software to create mobile game apps for Android and iOS? I am using a free version of Unity 3D and planning it to sell my current game app I've created by publishing it to Google Play. I also use this method for earning money by setting as a free app with ads on it.


I saw some developers relied on using free version of Unity 3D to create games and published it via App Store or Google Play. If it does, should I have to pay or share contribution to the Unity development team for earnings since I use the free version in order to rely for producing several game apps for business?



Answer



From the Unity FAQ:



Can we sell games and make money with the free version of Unity?


Yes you can create and sell a game with the free version of Unity, without paying royalties or any revenue share. However, the free version of Unity may not be licensed by a commercial entity with annual gross revenues (based on fiscal year) in excess of US$100,000, or by an educational, non-profit or government entity with an annual budget of over US$100,000.


Please also be aware that the feature set of the free version is not intended for the production of professional games and interactive content. Lastly, games made with our Pro trial licenses may not be distributed nor used for commercial purposes.




headlinese - Why do my "How to" questions often get renamed to "How do I"?


On the other hand the edit that fix mistype in "How to" got though community approval.


What is the rule about "How to" and "How do I"? Why are some tutorials called "How to"s?




Answer



When you are asking a question about how to do something, the preferred way to ask would be to use "How do I..." (or "How can I...", or "Where would I..."):



How do I plant flowers in my garden?
How do I transpose flute music for clarinet?
How can I get my two-year-old to stop misbehaving?
Where can I get more information about asking questions in English?



If I am answering such questions in written form (say, on a blog, or in a book), a good way to summarize this information in a concise title is to use "How to..." (or "Where to..."):




How to plant flowers in your garden
How to transpose flute music for clarinet
How to stop your two-year-old from misbehaving
Where to get more information about asking questions in English



Essentially, How do's are questions, and How to's are declarations.




In the title of a Stack Exchange question, either one can work.



How do I get a mailchimp list name and list id using php?




That works fine; you are essentially asking your question in the title of your question.



How to get a mailchimp list name and list id using php



That works fine, too. You are essentially giving a title to what you hope will be a set of answers to your question.


c++ - Object pools for efficient resource management


How can I avoid using default new() to create each object?


My previous demo had very unpleasant framerate hiccups during dynamic memory allocations (usually, when arrays are resized), and creating lots of small objects which often contain one pointer to some DirectX resource seems like an awful lot of waste.


I'm thinking about:




  1. Creating a master look-up table to refer to objects by handles (for safety & ease of serialization), much like EntityList in source engine




  2. Creating a templated object pool, which will store items contiguously (more cache-friendly, fast iteration, etc.) and the stored elements will be accessed (by external systems) via the global lookup table.





The object pool will use the swap-with-last trick for fast removal (it will invoke the object's ~destructor first) and will update the corresponding indices in the global table accordingly (when growing/shrinking/moving elements). The elements will be copied via plain memcpy().


Is it a good idea? Will it be safe to store objects of non-POD types (e.g. pointers, vtable) in such containers?


Related post: Dynamic Memory Allocation and Memory Management




Tuesday, August 23, 2016

determiners - psychologist John Hayes (THE, zero article before false titles)


An example (from The New Yorker) of a phrase with a false title (psychologist John Hayes):



After Simon and Chase’s paper, for example, the psychologist John Hayes looked at seventy-six famous classical composers and found that, in almost every case, those composers did not create their greatest work until they had been composing for at least ten years.



Both THE and the zero article could be used with false titles, but which looks better in this sentence to a native speaker? Would this look OK:



After Simon and Chase’s paper, for example, _ psychologist John Hayes looked at seventy-six famous classical composers and found that, in almost every case, those composers did not create their greatest work until they had been composing for at least ten years.




What if we beefed up the phrase with an adjunct? Would 0 and THE both look fine?



After Simon and Chase’s paper, for example, (Ø/the) cognitive psychologist John Hayes looked at seventy-six famous classical composers and found that, in almost every case, those composers did not create their greatest work until they had been composing for at least ten years.


After Simon and Chase’s paper, for example, (Ø/the) American cognitive psychologist John Hayes looked at seventy-six famous classical composers and found that, in almost every case, those composers did not create their greatest work until they had been composing for at least ten years.



It seems that THE looks O.K. when a false title is short ("psychologist") but starts looking strange before some complex combinations.



Answer



When both options are acceptable, it's very hard (if not impossible) to tell which would "look better" without larger context.


To me, they both mean the same thing, however the emphasis is slightly different. In this particular quote, with the ∅ article, a bit more emphasis seems to be on the name of the individual:




After Simon and Chase’s paper, for example, psychologist John Hayes looked at seventy-six famous classical composers...



With the definite article, though, some of the emphasis seems to shift to the title:



After Simon and Chase’s paper, for example, the psychologist John Hayes looked at seventy-six famous classical composers...



So, if you're more interested in conveying who did the study, perhaps the ∅ article would work slightly better. On the other hand, if you want to emphasize that person's field of expertise, then it may be better to include the definite article.


In this particular instance, that latter option might work well when researchers from several different areas studied the problem – psychologists, human factors engineers, social scientists, anthropologists, etc. – but you want to emphasize this was a psychological study. However, the former might work better if several psychiatrists studied the problem, but we were interested only in examining Hayes' findings.


It should be noted this is difference is very, very subtle, and not all readers may not interpret it in the same way. I'm not giving rules to be dogmatic about, I'm giving considerations to ponder. I will stand by this one point: you can't always tell the best option when you look at only a single sentence; you need to look at what else is in the paragraph, and even what else is in the surrounding text.



How to understand the preposition "with"?



She is popular with the young people.



Why use "with" here?


How should I understand the preposition "with" in this context?




Monday, August 22, 2016

Camera Control Techniques in Games


I am an MPhil student in Computing Science working on the problem of camera control in graphics. Though the literature of camera control dates back to the end of 1980s, the majority of them (up to my knowledge) is mainly academic and rarely used in games.


Now part of my thesis should be dedicated to camera control methods used in games. But the problem is that I have not implemented all the games in the world, so I can't speak about them. But I suppose there are some references that game developers usually use.


Can anybody help me with this? Even if it is from your own experience rather than a book.




legalese - Why mustn't the negatives be cancelled in: 'enumeration … does not presuppose something not enumerated'?


Source: United States v. Lopez, 1995, US Supreme Court, majority opinion by Rehnquist



To uphold the Government's contentions here, we have to pile inference upon inference in a manner that would bid fair to convert congressional authority under the Commerce Clause to a general police power of the sort retained by the States. Admittedly, some of our prior cases have taken long steps down that road, giving great deference to congressional action. The broad language in these opinions has suggested the possibility of additional expansion, but we decline here to proceed any further. [1.] To do so would require us to conclude that the Constitution's enumeration of powers does not presuppose something not enumerated, and that there never will be a distinction between what is truly national and what is truly local. This we are unwilling to do.



1. This superlative answer and its use of logic especially helped me, but doesn't duplicate this; I still wouldn't know how to parse the bold text until after determining that the negatives in the bold text mustn't be cancelled. Why not though? How can you discover or foreknow so?


2. This question reaffirms my categorical misunderstanding of StoneyB's answer and my gnawing plight with negatives. So how can I learn about and delve into 'cancellations', 'predications', 'scopes'?




Sunday, August 21, 2016

phrase usage - What is difference between "loosen" and "unscrew" for lid/cap?


For example, could you help me "loosen" or "unscrew" this lid/cap? Which one is correct and more common?




voxels - How to flatten out terrain and make better caves with Perlin noise


I'm currently using Perlin noise to generate a terrain. This is my actual attempt to create caves. I do get some sort of cave structures but they are small and are always close to the edges of the terrain. Also my terrain looks very irregular I'd like to have a more flat terrain. I've been playing with the values I pass to the Perlin noise function but I can't seem to get something good.


Do you have any pointers or suggestions to my actual approach in order to get something more regular within the Minecraft standards?



Answer



Terrain generation falls under the form part of development. It's an artistic endeavor, so I'm not so sure there's a correct answer. However, I can try to tell you about the knobs you can turn to get different results, and it'll be up to you to turn them to get the result you want.





  • Compress/expand: You can stretch or shrink the noise along a specific axis to alter the features of your terrain. This would primarily be useful on the Y axis, but would also work when used on the X and Z together. For example, if you want flatter terrain, apply a factor of .2f to the Y input on your noise function. Or if you wanted wider valleys and hills, you could expand the X and Z axis to stretch the noise out over a larger area.




  • Mixing noise: You can have multiple noise functions and combine them for interesting effects. For example, always choosing the maximum between your two noise values will give you more features (hills, peaks, etc.).



    • Noise selector: You can even use a third noise value as a selector to choose between two noise values. This is a good way of generating cliff faces and dramatic changes in landscape. I used this technique with some success in my game.



  • 2D noise with 3D noise: You can use a 2D height map to limit your 3D noise. This makes it far easier to control the surface of your world and vastly reduces weird features like floating islands.


  • Caves: Likely the easiest way to generate caves is to make them in a later stage of generation and remove them from the existing terrain. There's a bunch of methods to use, and it totally depends on what kind of caves you want. You can use simple 3D noise with a very low cut off between solid/air. Or you can use noise like Perlin worms to generate special noise that works well for caves.


I suggest you set up your code in such a way that you can easily change values and generate a new map, preferably without rebuilding. You need to be able to quickly test changes in your values so you can start to find the input values that work with your algorithm to give you the results you want.


Saturday, August 20, 2016

How can I handle different keyboard layouts?


Let's say I have a game that uses WASD controls on a QWERTY layout. Trying to use these controls on, say, a Dvorak layout is not ideal (equivalent to on QWERTY). Obviously, I'd want to use the same physical keys as QWERTY would use (,aoe on DVORAK).



I've come up with a few possible solutions:



  • Force the user to use QWERTY

    • obviously not ideal, especially for international users



  • Change shortcuts based on keyboard layout (WASD -> ,aoe)

    • forces me to make layout maps for each supported layout (automatable)


    • easiest for the user if there are more shortcuts than just WASD



  • Force the user to define shortcuts themselves

    • More flexible

    • Annoying if there are lots of shortcuts

    • Can be used in conjunction with the second option




  • Use hardware keycodes

    • consistent across keyboards?




How is this type of thing usually handled?



Answer



Listen for scan codes. How this is done depends on your OS, which you did not list. On Windows, you can get the scancode for a given virtual key code from WM_KEYDOWN and friends by using MapVirtualKey. Scan codes are based on the physical key and are unaffected by layout.


Have a quick read of http://www.altdevblogaday.com/2011/10/02/i-never-managed-to-go-left-on-first-try/.



So yes, as Nicol Bolas said, you can and should let users work around it. But just making it work right out of the box is not hard and your users will appreciate it.


Note that you are (probably) handling character input wrong, like the vast majority of game developers. Make sure that for text, you always use WM_CHAR (or the equivalent on other OSes) rather than using WM_KEYDOWN for text input. It is completely wrong to assume that when the 'a' key is pressed that you should input an 'a' to a text input control, due to the use of Dead Keys on some layouts. You can also support IME (or OS equivalent) for East Asian markets which have far more characters than can reasonably fit on a keyboard, and need special UI to type. Handling IME in a game is a pain (handling it at all is a pain), but worth it in my opinion to increase the appeal of your product to a much, much larger set of markets. Again, WM_KEYDOWN is never to be used for text, ever.


Vectors in game development


I'm new to programming and game programming. I've reading something about vectors and math, but I have a question - where do I use vectors in game programming? Maybe anyone can give a simple example where you are using vectors (in 2D)?


I've found examples but mostly they are in the console where they output numbers, and big examples which I don't understand.




Friday, August 19, 2016

verbs - The order of tenses


I have a question regarding the order of tenses. Even after looking at many graphs and questions, I couldn't quite figure out the place of present perfects.


I thought the order went from past perfect-> past simple-> present perfect-> present-> future.


Then I saw this example on a website:



The fans would like to have seen some improvement this year. ["Would like" describes a present condition; "to have seen" describes something prior to that time.]




Is would not past tense? How can the present perfect happen before the past tense?


If that is true, is one of these more correct than the other? I thought that the second one would be better since "present perfect" happened after "simple past", but now I'm not quite sure.



I did it as you've requested.



vs



I've done it as you requested.





transatlantic differences - To distinguish between American and British spelling



Words are :- theater, behavior , litre, dialogue , tire, program, omelette, cheque, pajamas, realize .




c# - Jittery Movement, Uncontrollably Rotating + Front of Sprite?


So I've been looking around to try and figure out how I make my sprite face my mouse. So far the sprite moves to where my mouse is by some vector math.


Now I'd like it to rotate and face the mouse as it moves. From what I've found this calculation seems to be what keeps reappearing:


Sprite Rotation = Atan2(Direction Vectors Y Position, Direction Vectors X Position)

I express it like so:


sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X);

If I just go with the above, the sprite seems to jitter left and right ever so slightly but never rotate out of that position. Seeing as Atan2 returns the rotation in radians I found another piece of calculation to add to the above which turns it into degrees:


sp.Rotation = (float)Math.Atan2(directionV.Y, directionV.X) * 180 / PI;


Now the sprite rotates. Problem is that it spins uncontrollably the closer it comes to the mouse. One of the problems with the above calculation is that it assumes that +y goes up rather than down on the screen. As I recorded in these two videos, the first part is the slightly jittery movement (A lot more visible when not recording) and then with the added rotation:


Jittery Movement


So my questions are:



  1. How do I fix that weird Jittery movement when the sprite stands still? Some have suggested to make some kind of "snap" where I set the position of the sprite directly to the mouse position when it's really close. But no matter what I do the snapping is noticeable.

  2. How do I make the sprite stop spinning uncontrollably?

  3. Is it possible to simply define the front of the sprite and use that to make it "face" the right way?



Answer




Only change the rotation whenever your distance is above a certain delta. Also center your sprite, right now you're using the top-left corner of the sprite.


Component based architecture: "pure" or some inheritance?


(I asked a similar question, but it had more questions inside it and I feel it wasn't clear enough, so I'm opening a new one).



Until recently I implemented all my games using an inheritance hierarchy. Those were simple games.


For example:


          Entity
/ \
Movable Static
/ \ / \
Orc Mage Tree Wall

This worked for simple games.


However recently I read about 'entity component systems'. Using this approach, a class doesn't inherit from another class in order to receive functionality. Instead it is composed with it, which allows for more flexible designs.



My question is this:


I know that each component is a class (derived from a common base class).


However, there is one thing I don't understand: In the 'component system' approach, is there one class that all entities are instances of - and the only difference between entities is the components they contain?


For example: There is a class Entity. All entities in the game are instances of this class.


The only differences between them is that they are composed with different Component objects.


For example:


Component aiComponent = new AIComponent();
Component movementComponent = new MovementComponent();
Component physicsComponent = new PhysicsComponent();
Component rangedAttackComponent = new RangedAttackComponent();


Entity orc = new Entity();
orc.addComponent(aiComponent);
orc.addComponent(movementComponent);
orc.addComponent(physicsComponent);

Entity shootingCastle = new Entity();
shootingCastle.addComponent(aiComponent);
shootingCastle.addComponent(rangedAttackComponent);
shootingCastle.addComponent(physicsComponent);


All of this as opposed to my old approach:


Orc orc1 = new Orc();
ShootingCastle castle1 = new ShootingCastle();

As you can see, both orc and shootingCastle are instances of the Entity class. But they are composed with different components.


Is this how 'entity component systems' are supposed to be? No inheritance hierarchy at all? Or is there still a basic inheritance hierarchy, but most of the logic is inside components?




mmo - What data structure should I use for a Diablo/WoW-style talent tree?


I'm considering implementing a talent-tree system for an online RPG, similar to that seen in World of Warcraft, where acquiring a skill unlocks the next "tier" beneath it in the tree.


Does anyone know of the best way of implementing this structurally in the database/code?



Answer



Use a structure like this to represent a tree in a database:


#Talent

id parent description
1 0 Tackle
2 1 Kick
3 1 Punch
4 3 Fire Punch

And another table to represent acquired talents per user


#UserTalent
id user talent
1 4 1

2 4 3
3 4 4

You can check for talent dependencies programatically by querying the complete talent table, and building a linked tree. You can also do that with SQL but it will require either recursive subselects or lots of queries. Better do it in your code.


If there are multiple dependencies, like for example Fire Punch depends on Punch AND Immolation use two tables to represent the dependency graph:


#Talent
id description
1 Tackle
2 Kick
3 Punch

4 Fire Punch
5 Immolation

#Depedency
id parent child
1 0 1
2 0 5
3 1 2
4 1 3
5 3 4

6 5 4

Thursday, August 18, 2016

word choice - What job should I have or What job I should have?



I want to ask myself what kind of job I'm gonna do. I want to know which one should be ok:




  1. What job should I have?

  2. What job I should have?


Thanks,



Answer



If it is a direct question , then the first sentence is correct: What job should I have?". If it is an indirect question like,"I I want to ask myself what job I shoud have?",the second option is correct. An indirect sentence the verb is in the affirmative. Another example: direct question= "What did yoy make for dinner?" indirect question= Bob asked me what I had made for dinner.


xna - Increasing efficiency of N-Body gravity simulation


I'm making a space exploration type game, it will have many planets and other objects that will all have realistic gravity. I currently have a system in place that works, but if the number of planets goes above 70, the FPS decreases an practically exponential rates. I'm making it in C# and XNA.


My guess is that I should be able to do gravity calculations between 100 objects without this kind of strain, so clearly my method is not as efficient as it should be.


I have two files, Gravity.cs and EntityEngine.cs. Gravity manages JUST the gravity calculations, EntityEngine creates an instance of Gravity and runs it, along with other entity related methods.


EntityEngine.cs


        public void Update()
{
foreach (KeyValuePair e in Entities)
{

e.Value.Update();
}

gravity.Update();
}

(Only relevant piece of code from EntityEngine, self explanatory. When an instance of Gravity is made in entityEngine, it passes itself (this) into it, so that gravity can have access to entityEngine.Entities (a dictionary of all planet objects))


Gravity.cs


namespace ExplorationEngine
{

public class Gravity
{
private EntityEngine entityEngine;
private Vector2 Force;
private Vector2 VecForce;
private float distance;
private float mult;

public Gravity(EntityEngine e)
{

entityEngine = e;
}


public void Update()
{
//First loop
foreach (KeyValuePair e in entityEngine.Entities)
{
//Reset the force vector

Force = new Vector2();

//Second loop
foreach (KeyValuePair e2 in entityEngine.Entities)
{
//Make sure the second value is not the current value from the first loop
if (e2.Value != e.Value )
{
//Find the distance between the two objects. Because Fg = G * ((M1 * M2) / r^2), using Vector2.Distance() and then squaring it
//is pointless and inefficient because distance uses a sqrt, squaring the result simple cancels that sqrt.

distance = Vector2.DistanceSquared(e2.Value.Position, e.Value.Position);

//This makes sure that two planets do not attract eachother if they are touching, completely unnecessary when I add collision,
//For now it just makes it so that the planets are not glitchy, performance is not significantly improved by removing this IF
if (Math.Sqrt(distance) > (e.Value.Texture.Width / 2 + e2.Value.Texture.Width / 2))
{
//Calculate the magnitude of Fg (I'm using my own gravitational constant (G) for the sake of time (I know it's 1 at the moment, but I've been changing it)
mult = 1.0f * ((e.Value.Mass * e2.Value.Mass) / distance);

//Calculate the direction of the force, simply subtracting the positions and normalizing works, this fixes diagonal vectors

//from having a larger value, and basically makes VecForce a direction.
VecForce = e2.Value.Position - e.Value.Position;
VecForce.Normalize();

//Add the vector for each planet in the second loop to a force var.
Force = Vector2.Add(Force, VecForce * mult);
//I have tried Force += VecForce * mult, and have not noticed much of an increase in speed.
}
}
}


//Add that force to the first loop's planet's position (later on I'll instead add to acceleration, to account for inertia)
e.Value.Position += Force;
}

}

}
}


I have used various tips (about gravity optimizing, not threading) from THIS question (that I made yesterday). I've made this gravity method (Gravity.Update) as efficient as I know how to make it. This O(N^2) algorithm still seems to be eating up all of my CPU power though.


Here is a LINK (google drive, go to File > download, keep .Exe with the content folder, you will need XNA Framework 4.0 Redist. if you don't already have it) to the current version of my game. Left click makes a planet, right click removes the last planet. Mouse moves the camera, scroll wheel zooms in and out. Watch the FPS and Planet Count to see what I mean about performance issues past 70 planets. (ALL 70 planets must be moving, I've had 100 stationary planets and only 5 or so moving ones while still having 300 fps, the issue arises when 70+ are moving around)


After 70 planets are made, performance tanks exponentially. With < 70 planets, I get 330 fps (I have it capped at 300). At 90 planets, the FPS is about 2, more than that and it sticks around at 0 FPS. Strangely enough, when all planets are stationary, the FPS climbs back up to around 300, but as soon as something moves, it goes right back down to what it was, I have no systems in place to make this happen, it just does.


I considered multithreading, but that previous question I asked taught me a thing or two, and I see now that that's not a viable option.


I've also thought maybe I could do the calculations on my GPU instead, though I don't think it should be necessary. I also do not know how to do this, it is not a simple concept and I want to avoid it unless someone knows a really noob friendly simple way to do it that will work for an n-body gravity calculation. (I have an NVidia gtx 660)


Lastly I've considered using a quadtree type system. (Barnes Hut simulation) I've been told (in the previous question) that this is a good method that is commonly used, and it seems logical and straightforward, however the implementation is way over my head and I haven't found a good tutorial for C# yet that explains it in a way I can understand, or uses code I can eventually figure out.


So my question is this: How can I make my gravity method more efficient, allowing me to use more than 100 objects (I can render 1000 planets with constant 300+ FPS without gravity calculations), and if I can't do much to improve performance (including some kind of quadtree system), could I use my GPU to do the calculations?



Answer



Your approach and implementation are valid (disregarding that position += force line). As long as there is only one instance of gravity. There is nothing in the code you have provided that leads to an over-O(n²) runtime. Therefore it is reasonable to expect a drop in framerate by half at 100 planets. That is 100 planets at 150fps. 200 planets at 30fps. etc.


As this does not match with your observations some questions arise. Most prominently: Are you sure the fps are lost in gravity.Update? Have you measured it with a profiler? Which statement is the offender? Is there any notable difference in memory consumption? Is the garbage collector busy? Can you render 100-200 planets at 300fps when there is no gravity?



Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...