Monday, August 31, 2015

meaning in context - "It was an admission that all might not be right between them." What does this sentence mean?


I am reading "Ender's Game", and I can't figure out what it means when I come across this sentence.


Here is the context:




“Here, snag my hand!” Alai called.


Ender held out his hand. Alai took the shock of impact and helped Ender make a fairly gentle landing against the wall.


“That’s good,” Ender said. “We ought to practice that kind of thing.”


“That’s what I thought, only everybody’s turning to butter out there,” Alai said. “What happens if we get out there together? We should be able to shove each other in opposite directions.”


“Yeah.”


“OK?”


It was an admission that all might not be right between them. Is it OK for us to do something together? Ender’s answer was to take Alai by the wrist and get ready to push off.”



I think "all might not be right" could be a idiom, but find nothing when I google "all might not be right".


Or, "all might not be right" is a specific use of "all not" phrase? It is "all something might not be right between them. And that something is left out? And I can replace "all something might not be right" with "something might not all be right" without changing the meaning of the sentence?




Answer



There are at least three things going on here which may be confusing you.




  1. The final clause that all might not be right with them acts as the complement to the noun admission.


    You probably know that many verbs take complements—direct objects, indirect objects, predicative complements, and so forth—but you may not be aware that adjectives and nouns take complements, too. The adjective ready, for instance takes two sorts of complement: preposition phrases (PP) with for (ready for dinner) and infinitive clauses (IC) (ready to have dinner). The noun idea takes (among other things) PP with of and for (the idea of having dinner, an idea for dinner) and what are sometimes called ‘content clauses’ (CC) headed by that (‘an idea that dinner will be soon*).


    Nouns which are derived from transitive verbs are particularly likely to take complements to express the object of the action, and that is the case with admission: it is derived from admit and both the verb and the noun may take a CC as complement:



    He admitted his guilt.
    He admitted that he was guilty.

    ... his admission that he was guilty ...



    So in your example, that all might not be right with them is what Alai admitted.




  2. In the complement clause, all acts as the subject with the syntactic force of a noun phrase and the meaning ‘everything’. This use was once common, but it’s relatively rare today, when we mostly use all as a quantifier or an adverbial. All is... and all are... have a distinctly literary ring; if you Google-book them you will find that most 21st-century hits are religious or philosophical, or historical reprints.


    This is probably why you are more comfortable with “all something might ... ” or “... might not all be right”. But ‘nominal’ all still hangs around in a handful of fixed phrases such as all is well and all is lost—and all is right with such-and-such. All is right with them means Everything’s OK with them.




  3. ‘Nominal’ all behaves oddly with negation. If you want to negate a statement about every X or everyX or with all X, particularly if you need to make it clear that what you mean is that you are asserting that the statement is not true of {all/every} X but only of some X, you put your not in front of all/every:




    Not all pronouns have a distinct objective form.
    Not everybody loves Raymond.



    But old-fashioned ‘nominal’ all carries along an older, less specific negative, with not after the verb. All might not be right means





It was possible that not everything was right between them—some things might be wrong.






I’m deliberately weaseling here in saying ‘syntactic force’, because grammarians are undecided whether to call this use a pronoun, a noun, or a ‘fused-head determiner’. Don’t worry about it; it doesn’t really matter what you call it as long as you understand what it’s doing.


xna - How to generate Spritefonts for monogame


I just want to render some text to the screen using:




  • monogame 3.0

  • MS Visual Studio 2010 C# Express


In XNA, you were able to add fonts to the content pipeline quite easily. But this doesn't seem to be the case in monogame. Loading TTF Files using Content.Load() doesn't work. Is there any way to generate or download *.spritefont files or *.xnb files containing the font data (without resorting to install XNA)?



Answer



An alternative is to use pre-generated bitmap fonts instead. Here's a tutorial I wrote a while back on using the BMFont tool to get text into your game using the MonoGame.Extended library.


http://dylanwilson.net/bmfont-rendering-with-monogame-extended


meaning of 'tick off something to someone" here


This is from an article in The New York Times: Fox News v. Robert Mueller



If only we could dismiss Sean Hannity, Jeanine Pirro, Laura Ingraham and the other well-paid propagandists at Fox News as though they were harmless drunks at the end of the bar, ticking off their conspiracy theories to anyone who will listen. Unfortunately, the guy sitting on the next stool is the president of the United States, and he’s all ears.




I've looked up several dictionaries for "tick off." Mainly there are three meanings: "infuriate", "reprimand", and "to mark some item on a list"


I am going with the last one, but having a hard time clearly understanding the context. I kind of have a guess though. Is it something like "enumerating/pointing out/laying out their conspiracy theories to someone"?



Answer



A disgruntled spouse might "tick off" a list of grievances.


The verb tick off (to enumerate, as J.R. aptly suggests) was not a good choice here by the NYTimes author, as these talking heads tend to foam at the mouth when delivering their theories. Rabid dogs do not enumerate. Their attacks on Mueller are disgraceful. Perhaps the verb tick off struck the author as less hackneyed than "rattle off". Conspiracy theories are typically "rattled off", a dismissive verb that suggests a certain emptiness between the ears.


Mnemonics for learning the days of the week


I can't memorize and repeat quickly the days of the week even though I studied English for several years (I always need to count with my fingers). How are the name of the days taught to children? Is there a song, a doggerel or something else?




Can we use the present perfect in this case?


In Korea, we learned that we should use the past tense when the subject is an historical event, as in "The Korean war broke out in 1950."


However, I think that when the event continues to affect the present (now), we should use the present perfect.



So I think that we can say 'The Korean war has broken out in 1950.'


Am I right?




pronunciation - Negative numbers: "minus" or "negative"?



I noticed that when negative number are used in speech, there are two dominant patterns. Taking "-10" as an example, in some cases it is pronounced "negative ten", while in others it is "minus ten".


I could not find any rules for this. A discussion in MathOverflow (which was closed) suggested that using negative was introduced in the US by "New Math" since the 1960's. If this is true, I would expect non-American speakers to mainly use minus (which I think is similar to the usage in most foreign languages), and perhaps senior Americans as well.


I'm not asking for opinions about this argument here. I'm also not looking for explanations or reasons for preference of one or another or the like.


I am looking for




  1. References for authoritative text if there is any




  2. Evidence of usage: I'd like to know how different dialects call negative numbers, and if there are rules or conventions for using e.g. "minus 40" or "negative 40" in different contexts in the same dialect.







java - How to play animations (GIF, SWF... )?


I have many diffrent animations made with flash.
I can make it as (1).SWF, (2).GIF or as (3).PNG (every Frame per second).

Searched in google... but coudn't find anything usefull.




  1. SWF: For SWF i need Flash on the android phone... this is something new to me and because of that i woudn't prefer a solution with that.
    -> I heard that Flash is not supported on Android for a long time, so this does not work.




  2. GIF: If that is possible it woud be very nice. I'm thinking of something like "animation1.start();".
    But i heard that android can't handle GIF.. -.-





  3. PNG: I know how to animate many .png pictures with an animationdrawable but when i export the animations into a .png for every frame in the second... imagion how many pictures i have. The problem is that i can't make subdirectorys in the drawable folder. Why? I don't have a clue. :/ But realy, that woud suck.




Do anyone have any solution to that than pls feel free to tell me. :)


Edit: I didn't finde a easy solution so i will make it with animationdrawables.
If you have a solution... pls pls answer here :)



Answer



Export to PNG and use a texture packer to create one texture-atlas/spritesheet.


https://code.google.com/p/libgdx-texturepacker-gui/

or
http://www.codeandweb.com/texturepacker


These texturepacker export a text file( usually a json file ). This file contains all coordinate data. If you plan on using your own implementation look at the LibGDX source code and see how its making use of texture packer files.


Edit:


Because you are rather new to gamedev, it would be way easier if you just used LibGDX. If you insist on doing your own things then:


With libgdx-texturepacker-gui: first you need to understand how json works. If i'm not mistaken in the package android.util there should be a jsonreader class. You need to parse the json file and read the coordinates you need to clip the image with when you draw it. There is an example that comes with the zip file called "test-me". It shows how to pack textures.


Open the project in that folder and hit : Pack selected. It will create some files in the output folder. It will create a png ( your sheet/atlas ) and .pack file ( your json file you can open it with notepad or any other text editor and read what created based on those images)


For animations you need to do some extra work, because you create sequences based on the region names ( that's why you just need to use something like libgdx, it's all done for you).


withtexturepacker: There are several formats it can export too, but that's up to you. Same story as above you need to parse the file and need to create a function to get the region you want.


Alternatively you don't use a texture packer and create the texture atlas yourself by placing the images uniform in a sequence like so:



[][][][][]        <---- animation 1 : 5 frames
[][][] <---- animation 2 : 3 frames
[][][][][][][][] <---- animation 3 : 8 frames
[][] <---- animation 4 : 2 frames

But you will not only waste space on your atlast ( meaning it might consume more memory ), you still have to write something that disects every sequence.


Sunday, August 30, 2015

algorithm - Diamond-square terrain generation problem


I've implemented a diamond-square algorithm according to this article: http://www.lighthouse3d.com/opengl/terrain/index.php?mpd2


The problem is that I get these steep cliffs all over the map. It happens on the edges, when the terrain is recursively subdivided:


enter image description here


Here is the source:



void DiamondSquare(unsigned x1,unsigned y1,unsigned x2,unsigned y2,float range)
{
int c1 = (int)x2 - (int)x1;
int c2 = (int)y2 - (int)y1;
unsigned hx = (x2 - x1)/2;
unsigned hy = (y2 - y1)/2;
if((c1 <= 1) || (c2 <= 1))
return;

// Diamond stage

float a = m_heightmap[x1][y1];
float b = m_heightmap[x2][y1];
float c = m_heightmap[x1][y2];
float d = m_heightmap[x2][y2];
float e = (a+b+c+d) / 4 + GetRnd() * range;

m_heightmap[x1 + hx][y1 + hy] = e;

// Square stage
float f = (a + c + e + e) / 4 + GetRnd() * range;

m_heightmap[x1][y1+hy] = f;
float g = (a + b + e + e) / 4 + GetRnd() * range;
m_heightmap[x1+hx][y1] = g;
float h = (b + d + e + e) / 4 + GetRnd() * range;
m_heightmap[x2][y1+hy] = h;
float i = (c + d + e + e) / 4 + GetRnd() * range;
m_heightmap[x1+hx][y2] = i;

DiamondSquare(x1, y1, x1+hx, y1+hy, range / 2.0); // Upper left
DiamondSquare(x1+hx, y1, x2, y1+hy, range / 2.0); // Upper right

DiamondSquare(x1, y1+hy, x1+hx, y2, range / 2.0); // Lower left
DiamondSquare(x1+hx, y1+hy, x2, y2, range / 2.0); // Lower right

}


Parameters: (x1,y1),(x2,y2) - coordinates that define a region on a heightmap (default (0,0)(128,128)). range - basically max. height. (default 32)


Help would be greatly appreciated.




directx - Point Light Soft Shadows


How to implement soft shadows for omni directional (point) light. We use typical shadow mapping technique. Depth is rendered to texture cube and addresing is pretty simple then. Just using vector from light to fragments world position. It works perfectly. Until you want soft shadows. In our engine we use PCSS technique for spot lights. But for point light there begins troubles.


How to sample in 3D?


I developed technique when orthonormal basis is created from a direction and upvector (0,1,0). And then multiply sampling vector (something like this (1.0,i/depthMapSize,j/depthMapSize) with this basis. But this (of course :)) looks pretty bad for vectors near (0,1,0) and (0,-1,0).


I will appreciate any help on this.




xna - Quad Tree with a lot of Moving Objects


I have a Quad Tree implementation that is very useful for what I am trying to do. My problem is that when my viewport has a lot of objects, the Update for the Quad Tree takes a very long time.


It is a known fact that Quad Trees are slow for non-static objects. I tried a few methods to try to speed things up, but the fact is, I need to update a large number of objects very often.


Is there a better algorithm I should be looking at instead? Are there some derived Quad Tree implementations you know about that might be useful to me?



Answer



How are you moving Quad Tree objects? The simplest (and slowest) method is to remove the object and re-insert it. The open-source XNA Quad Tree me and a friend made does a little bit of logic when an object moves:


If the object is still inside the same quad
if the object fits into a child quad

Add to child
Else
move the object to the parent(s) until it fits, and optionally going back down into children

If you're already doing something like that, it could be worth looking into other spatial index methods like Spatial Hashing.


rotation - Rotate an object around a point in Ogre3D




Possible Duplicate:
How can I rotate about an arbitrary point in 3D (instead of the origin)?



I am new to 3D programming and I have been using Ogre3D lately to get a grasp of it.


What I am trying to do is the following:


Image rotation


I want to make an entity rotate around a point (probably the parent SceneNode) in a circular way only in the X and Z axis.


I have tried using yaw/pitch/roll and rotate but no luck, and I can't find any good tutorials/how-tos online.




Answer



I finally did it using the following pseudo-code:


parent = sceneMgr->getRootSceneNode()->createChildSceneNode();
child = parent->createChildSceneNode();
child->attachObject(entity);
child->translate(10,0,0);
parent ->rotate(Ogre::Quaternion(Ogre::Degree(10), Ogre::Vector3(1,0,0)) , Ogre::Node::TransformSpace::TS_WORLD);

For anyone who has the same problem as me.


xna - Debugging tips?



I'm new to games programming and I'm working on a C#/XNA project.


Something I'm spending a lot of time on is debugging. Obviously as games run in a loop finding the exact iteration that a bad condition has occurred can be tricky.


Spending time setting up conditional breakpoints certainly helps but eats up time.


Are there some ninja tips out there for helping to track down the precise moment things go bad that you guys use?



Answer





  • Kind of a simple advice here but a little something that I found very useful is displaying debugging strings/rectangles to the screen.


    You can print the player's current state, the enemy's animation state, the number of active bullets, the frames per second, etc. All these simple variables are what make up the core of your game, so it's essential that they work properly and a nice way to make sure they do so is to have debugging tools at hand.



    So, in addition to logging variables like Gajet proposed (which is a very good advice imho), you should also show these variables while your testing so you can clearly see when something is wrong.


    It may seem stupid, but it helped me find a lot of nasty bugs that I thought were much more complicated (I simply put red rectangles to show colliding tiles on a platformer, and I found out that the problem wasn't in the collision response code, but rather in the collision detection code).


    You'll start out with a debugging string tool, then move on to debugging shapes (rectangles or even lines to represent vectors), then to more complicated tools and you'll eventually end up with a pretty solid debugging toolbox that you can reuse over other projects (if you make sure your debug code is general enough to be independant of the game).




  • In addition to debugging tools, consider writing unit tests. I know it doesn't sound nice having to write tests for most functions from your game, but don't see it this way. Unit tests can save you a whole lot of time. For example, if your collision system is not working but you wrote enough unit tests for your collision detection, you can just look into your collision response code and find the bug.


    Not only does it tell you where to look for the bug, it also tells you when you break something after changing a few lines somewhere, because your tests won't pass anymore.




  • If unit tests are too much for you, then at least start adding assertions into your code. So, if something is obviously wrong (e.g. a character with negative health), your code will break right away and you won't waste your time too much.





A couple of advices that I learned the hard way. You may think some are useless, but try them out and see if they fit your debugging needs.


books - Where to start for implementing vehicle physics?



A little background for myself. I am relatively experienced with 3rd part physics engines such as Havok, Box2D, Bullet and have successfully integrated them in custom engine(s). I have also made a simple physics engine by following a few known books.



Now I am interested in diving into vehicle physics. There are a couple of books that skim over the topic but do not go over in enough detail for me to grasp anything useful. So I would like to know of good books/resources that are not too heavy (by that I mean a book that is pure vehicles and made for engineers rather than game developers) that help me get started on vehicle physics. Here get started = at least guide me through creating a simple vehicle in 3D with modern features found in most games (suspension/transmission etc.)


Note: I searched for a similar question but did not find one, but if one exists, please post the link and feel free to close the question.



Answer



This blog has four links (the third is broken), the first of which seems like an amazing resource, the others seem pretty great too. I'm probably going to read over this just for funsies, should be a good read.


You could take a look at the Rigs of Rods engine, it's an open source soft-body vehicule simulator, it may give you some insight into how it's done, but could be too complex for what you want to do. Also, reading though other people's code may not be what you want to do; nevertheless it could be inspiring.


Digital Rune gives some simple info on their implementation of car physics.


meaning in context - Introducing someone



Alexandra, let me introduce you. This is my wife Marilyn.



What does the first sentence mean?




Let me introduce you to my wife Marilyn.



or



Let me introduce my wife Marilyn to you.



or


They are both implied in the original sentence?



Answer



Actually, I think that's it's Marilyn who is being introduced to Alexandra in the original example sentence.



In order to illustrate, I need to set up a somewhat contrived context.


Let's assume that you are led by a police officer into a room where you stand behind a one-way mirror. Behind the mirror is a suspect sitting in a chair. Let's also say that your name is Mary and the suspect is Jessica.


The police officer says to you, "Mary, I'd like to introduce you to Jessica. We brought her in yesterday."


Because Jessica is not aware of any of this dialogue, she is not being given an introduction to anyone.


The recipient of the introduction is Mary, but the object of the introduction is Jessica.


Based on this, and returning to your original question, the most applicable sentence between the two you provided is:



Let me introduce you to my wife Marilyn.



Here, the same thing is occurring as in the police station example.



It's likely that Marilyn is present for this dialogue, but it's also possible that she isn't. Let's say that this sentence is said to Alexandra while she is standing on one side of a crowded room and Marilyn is on the other side.


By having said the first sentence, Marilyn has been pointed out and Alexandra has now been "introduced" to her, even though not in person.


Following this, the second sentence could now be said:



Let me introduce my wife Marilyn to you.



After which, Alexandra is led over to Marilyn—at which point Marilyn becomes the recipient of a second introduction, one in which Alexandra is now the object.




There are some issues with this because the grammar, on its own, can be ambiguous. In the second sentence, who is the recipient of the introduction and who is the object? Depending on interpretation, it could be either. (I simply interpreted it in one possible way.)


Also, in more normal circumstances, both people are aware of each other and the conversation at the same time. So, in that sense, it doesn't really matter: the introduction is "mutual."



Note that physical proximity also doesn't matter. If I lead somebody into a room by the hand, and then shout out, "Everybody, I'd like to introduce you to my friend!" my friend is the object of the introduction and "everybody" is the recipient of the introduction (whom I'm addressing).


But, ultimately, ask whom you're speaking to and whom you're talking about.


Saturday, August 29, 2015

personal pronouns - It is me who am to blame. It is I who am to blame



  1. It is me who am to blame.

  2. It is I who am to blame.


Which one is correct here?
I am bewildered about these two sentences.



Answer




You have got to remember one rule:



When who refers to a personal pronoun (I, you, he, she, we, they), it takes the verb that agrees with that pronoun.(See Source)



Examples :



It is I who am sorry.(I am sorry)


It is you who are responsible.(You are responsible)


It is we who are winning the bet.(We are winning the bet)


It is they who have been watching TV since morning.(They have been watching TV since morning)




Considering the above material:



Correct : It is I who am to blame.(I am to blame)


Incorrect : It is I who is to blame. (I is to blame doesn't make sense)



random - Unwanted Perlin Noise result


I've finally managed to write a working Lua version of Perlin's improved noise for Love 2D. However, when I run it, i get this:




Which is just fine, I guess. But I would like something that looks more like this:



How can I achieve this?



Answer



You will need to learn how the terms Octave, Persistence, Frequency, and Lacunarity are used. What you have is a good first step, it looks just like noise should.


The basic idea is that you need to combine multiple noise sources into one result to achieve the final look. This combination can be something simple like addition, but you can take many mathematical operations.


In the end a typical example for your grainy clouds looks like this: Map = Map1 + (Map2 / 2) + (Map3 / 4) + (Map4 / 8)


For reference and examples: Start here


antonyms - what is the opposite of the word 'flat'?



  • The surface of the colony* is flat and rugged.

  • The surface of the colony* is not flat and rugged.



*(a colony of fungi)


Flat is in this case refers to the elevation of the colony. From the side view, it's flat, like a computer disc.


What is the opposite of flat, for this context? Is it non-flat?




Pack of resources in one big file with XNA



Is it possible to pack all the little .xnb files into one big file? Given the level of abstraction of the XNA Framework I though this would come out of the box but I can't find any well integrated solution.


So far the best candidate is XnaZip but in addition to having to compile the resources in a post-build event, and a little trouble porting the game to XBOX I have to rename all the references to resources I have already implemented.



Answer



It's possible, but you either have to:



  • Find a library that does it for you, or

  • implement it yourself.


XNA lets you do the latter by deriving from the ContentManager class and replacing the OpenStream method; in fact, the documentation explicitly says:




protected virtual Stream OpenStream (string assetName)

Opens a stream for reading the specified asset. Derived classes can replace this to implement pack files or asset compression.



In the override version of OpenStream, one would simply return a compatible Stream that read the requested asset data from a pack file, rather than opening a FileStream from disk.


The tricky part is that you have to actually build the pack file yourself, incorporating the xnb files output via the content build pipeline. You could build a Content Pipeline Extension to do this, or find some other method, depending on what your goals are.


Minimum Viable Product for RTS game?


I'm in pre-production on a strategy game and am trying to determine if the core gameplay will be fun. A good technique to determine this is to strip the game down to its minimum viable product (MVP) and see if that is fun. If the MVP isn't fun, then no amount of extra content or features will make it fun.


I'm having difficulty determining the MVP for a strategy game as I'm a little too far into the weeds to see which of the many design features are core mechanics and which are unnecessary.


Purely as an example, lets just say StarCraft2 is the strategy game I want to make. What would be the MVP for SC2 to prove out that its core gameplay is fun?




Answer



Real-Time Strategy is a genre which actually combines multiple games in one. You have a management game (resource management and build orders), a puzzle game (building a base with a functional yet easy to defend layout), two different kinds of exploration games (exploring the map and exploring which units beat which other units), and a tactics game (controlling your units in battle). You obviously can't create all these five games at once, so you should just focus on one of them at first.


In this answer I am focusing on two of these games which I consider most essential to the genre: Unit controlling and base building.




  1. Create a player-controlled "tank" game object (represented as an untextured cube) on an empty plane which moves to a new position when the player clicks there.

  2. Add immobile AI targets (represented by a cube in a different color) which get deleted when their HP go below 0, and the ability for the tank to fire on the closest target to reduce its HP.

  3. Add the ability for the targets to shoot back when the player-tank is in range.


Now you have a playable strategy/puzzle game: Navigate your tank from target to target in a way that it doesn't fight more than one at a time and destroys them all before itself gets destroyed. This is basically how you attack a base with defensive turrets in an RTS game.



Next steps to pursue in no particular order:



  • Add a simple AI to the opponents so they can move and not just shoot back

  • Add multiple player units to control and the UI for selecting units

  • Add buildings (see "Base Building MVP" for details)

  • Add more types of units with different ranges, weapon strengths and hit points

  • Add blocking terrain to the map and route finding to the unit AI so they can navigate around it.

  • Replace the units with properly animated graphics

  • Add win and lose conditions





  1. Create an empty plane and allow the player to place a building on that plane by clicking

  2. Add different kinds of buildings and an UI which allows the player to choose which building to build

  3. Add construction times and resource counters

  4. Add buildings which create resources in regular intervals (I wouldn't implement worker-units yet because they require too much AI programming to work) and a ruleset for when you can build which building ("can only build a factory when you have at least one finished barracks").


Now you've implemented the first few minutes of a Starcraft game: Figuring out the ideal build order to get the buildings you want as fast as possible.


In fact you could stay here and polish it, and you have a simple resource management game. But if you are still sure you want to create an RTS, then the next steps would be in no particular order:




  • Add an AI which builds its own buildings

  • Add terrain features which prevent buildings from being built (or are a requirement for placing certain buildings, like "farms can only be built on fertile terrain")

  • Add mobile units (see "Unit Controlling MVP" for details) which can destroy enemy buildings

  • Add construction jobs to individual buildings which can be started, take a certain time to complete and can be aborted by the player.

  • Create building types which interact with each other in some way (in Starcraft, these would be Terran addons or Protoss pylons, for example)


I am looking forward to playing your game.


Friday, August 28, 2015

3d - Translate along local axis


I have an object with a position matrix and a rotation matrix (derived from a quaternion, but I digress). I'm able to translate this object along world-relative vectors, but I'm trying to figure out how to translate it along local-relative vectors. So if the object is tilted 45 degrees around its Z-axis the vector (1, 0, 0) would make it move to the upper right.


For world-space translations I simply turn the movement vector into a matrix and multiply it by the position matrix: position_mat = translation_mat * position_mat. For local-space translations I'd think I'd have to use the rotation matrix into that formula, but I see the object spin around instead when I apply a translation over time no matter where I multiply the rotation matrix.



Answer



Just take the desired movement vector, multiply it by the object's rotation matrix, then use the result as before, i.e. convert it to a translation matrix and multiply it into the position_mat.


verbs - would rather eat or ate?


Would rather (but not would prefer to) is also followed by a past tense when we want to involve other people in the action, even though it has a present or future meaning. Study the following:


a.Shall we go out for dinner tonight? ~ No, I'd rather we ate at home, if you don't mind.



b.My rephrased: Shall we go out for dinner tonight? ~ No, I'd rather we eat at home, if you don't mind.


I have extracted the italic parts from a grammar site, but would you tell me if the bold part is correct, too? If so, what is the difference between a. and b. semantically?




Thursday, August 27, 2015

word choice - Do you "slump on a bed" or "slump onto a bed?"



Is one of them the correct option? Or they mean different things?


On Google maps I got these results:


"slumped on the bed" (9K results)


"slumped onto the bed" (3K results)


Example sentence:




Without permission, he slumped on/onto my bed and lay on his back.




Answer



You can do either.


To slump is to ease from an erect posture to a relaxed one where the shoulders are hunched and there can also be a bend at the waist.


If you slump on the bed, you're on the bed, slumping.


If you slump (down) onto the bed, you come to rest on the bed as the end result of your slumping.


That's the basic difference of on and onto.


But some speakers may use on to mean onto.




He jumped on the stairs of the train as it began to pull out of the station.


He jumped onto the stairs of the train as it began to pull out of the station.



So, given this variation in usage in the speaking population, you cannot be sure exactly what is meant if the preposition is on in this context.


pronunciation - How to pronounce 'GB'?


If I want to buy a phone with 64 GB, how should I say it?


Should I say



"A phone with 64 gigabyte."




or



"A phone with 64 GB (simply pronounce the letter 'G' and 'B')."



which one is more native?




grammar - If zero and first conditional





If you are well-organised, you (manage OR will manage) your time.



Everyone in my test was saying "will manage" is the correct answer, but the way I understand it is this sentence is talking about a general truth in the present, or it's just explaining the former sentence.


If it were worded "If you become organised" I think the answer would be "will manage" then.


What is the correct answer?



Answer



It depends on context I think.


Discussing a general truth this one is correct




If you are well-organised, you manage your time.



However, perhaps someone is not always well organised, and you are talking about an upcoming task that might be time critical, you might say to them



If you are well-organised [in this task], you will [be able to] manage your time [effectively].



xna 4.0 - XNA Platformer Sample: Supporting multiple resolutions?



I have been looking at the XNA Platformer Sample and noticed that, when you change the resolution, the game world still renders at 800x480 and not the new width and height of the display.


Can anyone suggest a simple way to make the Platformer sample support multiple resolutions?



Answer



First of all, to test this answer on Windows, use a fresh copy of the game and add the following line to the constructor of PlatformerGame.


Window.AllowUserResizing = true;

This will let you resize the window and see the changes in action.




The easiest way is to simply scale the game so that it fits on screen. You need to pass a scaling matrix to SpriteBatch.Begin.


Here I have provided code to calculate a matrix that will "fit" the content into the available space and centre it:



var gameWorldSize = new Vector2(800, 480);
var vp = GraphicsDevice.Viewport;

float scaleX = vp.Width / gameWorldSize.X;
float scaleY = vp.Height / gameWorldSize.Y;
float scale = Math.Min(scaleX, scaleY);

float translateX = (vp.Width - (gameWorldSize.X * scale)) / 2f;
float translateY = (vp.Height - (gameWorldSize.Y * scale)) / 2f;


Matrix camera = Matrix.CreateScale(scale, scale, 1)
* Matrix.CreateTranslation(translateX, translateY, 0);

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera);

(Note the way that I scale by 1 and translate by 0 on the Z axis. Not modifying the Z axis of sprites is important when using SpriteBatch.)


Note that, when you scale the game like this, any graphics that are "pixel perfect" will no longer be perfectly aligned to any pixels. One way to solve this is to have multiple versions of your assets at different, fixed scales - draw them at fixed world sizes (not by their pixel size) and then only allow scale in the above code to be a set of fixed values matching those asset sizes.




The other way is to implement a scrolling camera (focused on the player). This is good because it allows the world to be any size, independent of the screen size.


var vp = GraphicsDevice.Viewport;


float translateX = vp.Width / 2 - level.Player.Position.X;
float translateY = vp.Height / 2 - level.Player.Position.Y;

Matrix camera = Matrix.CreateTranslation(translateX, translateY, 0);
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera);

A good camera will "lag" a little bit behind the player in order to feel more natural. You can find lots of tutorials on making a good platformer camera online.


Continuing on my notes about keeping assets fixed to the pixel grid: This method allows you to do this with a single set of assets. Just make sure your camera position is rounded to the nearest pixel if this is what you want to do.





Note that the HUD is - in the original sample - sharing the same sprite batch as the level display. This will cause HUD elements to appear in the wrong place. You should separate them out so that the HUD is not affected by the camera, like so:


spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera);
level.Draw(gameTime, spriteBatch);
spriteBatch.End();

spriteBatch.Begin();
DrawHud();
spriteBatch.End();




You can, of course, combine these approaches and come up with your own variations (like the fixed-scales-multiple-graphics-sets variation I suggested earlier). What you do will depend on the game you are making.


Obviously both methods require you to make the game world larger so that it looks nice when you can see beyond its edge. I'll leave this as an exercise.


There are a few other good questions on handling 2D game scaling on this site. Here is one such question.


Wednesday, August 26, 2015

personal pronouns - "than her" versus "than she"



It is a well known fact that Alex is more soft-spoken than (she/her).




Why would "her" be wrong? Why must the sentence end with "she"?




grammar - "How come" vs. "How come that"


I'm a English learner who studies syntax. I often refer to English corpus such as COCA to learn natural uses of English. Then, I found some sentences involving "how come", followed by "that" and a sentence, for example, as following:



How come that you have such good English? / How come that you eat hot food in hot countries?



I have thought that those correct sentences of how come should be like "How come you have such good English", where "that" is omitted.


I want to know how native speakers feel about those sentences that involve "that" between "how come" and a sentence. Are they correct? Is there any difference? Or, are they a sort of error-like ones?


Thank you.





Dangling modifier when the preposition is at the beginning of the sentence ("After", "by")


Which of the following sentences are correct?



After introducing some anchors by the user, the range of nodes which are affected by a single anchor or a group of anchors should be specified.


After some anchors are introduced by the user, the range of nodes which are affected by a single anchor or a group of anchors should be specified


After some anchors were introduced by the user, the range of nodes which are affected by a single anchor or a group of anchors should be specified



How about this.




After visiting a node which matches the anchor “PageNavigationBar”, the scope of the context is closed.


by selecting the two anchors from the list of anchors and selecting the “Common Ancestor” option, the context is created



I am afraid the way I use of subordinate clauses with "after" or "by" is incorrect or not natural or they can be cases of Dangling Modifiers


What is the general rule?




3d - How to rotate an object around world aligned axes?


I have a Vector3 which has an euler angle for each axis.


Usually, when I want to create a rotation matrix I will use functions such as D3DXMatrixRotationX passing the respective angle from my rotation vector above and multiply the matrices (ZXY) to create the overall rotation matrix which is used to form the complete object transformation matrix.


However, this method will produce a set of rotations in object space. That is, passing a vector of (90, 0, 90) into my method will create a rotation in world space effectively of (90, 90, 0).


Is there a way to always ensure each component of my rotation vector results in a rotation around the respective world space aligned axes?


EDIT:



This is an animation of what is currently happening - I want a way to rotate around the blue axes, not the red.


Euler Angles


EDIT 2:


Just to note I am not looking for a solution involving Euler angles, but simply a way in which I can represent a transformation of multiple rotations around the world axes.



Answer



Based on you comments, it seems that you're storing the orientation of the object as a set of Euler angles, and in/decrementing the angles when the player rotates the object. That is, you have something like this pseudocode:


// in player input handling:
if (axis == AXIS_X) object.angleX += dir;
else if (axis == AXIS_Y) object.angleY += dir;
else if (axis == AXIS_Z) object.angleZ += dir;


// in physics update and/or draw code:
matrix = eulerAnglesToMatrix(object.angleX, object.angleY, object.angleZ);

As Charles Beattie notes, because rotations don't commute, this won't work as expected unless the player rotates the object in the same order in which the eulerAnglesToMatrix() applies the rotations.


In particular, consider the following sequence of rotations:



  1. rotate object by x degrees around the X axis;

  2. rotate object by y degrees around the Y axis;

  3. rotate object by −x degrees around the X axis;


  4. rotate object by −y degrees around the Y axis.


In the naïve Euler angle representation, as implemented in the pseudocode above, these rotations will cancel out and the object will return to its original orientation. In the real world, this does not happen — if you don't believe me, grab a six-sided die or a Rubik's cube, let x = y = 90°, and try it out yourself!


The solution, as you note in your own answer, is to store the orientation of the object as a rotation matrix (or a quaternion), and update that matrix based on user input. That is, instead of the pseudocode above, you'd do something like this:


// in player input handling:
if (axis == AXIS_X) object.orientation *= eulerAnglesToMatrix(dir, 0, 0);
else if (axis == AXIS_Y) object.orientation *= eulerAnglesToMatrix(0, dir, 0);
else if (axis == AXIS_Z) object.orientation *= eulerAnglesToMatrix(0, 0, dir);

// in physics update and/or draw code:

matrix = object.orientation; // already in matrix form!

(Technically, since any rotation matrix or quaternion can be represented as a set of Euler angles, it is possible to use them to store the orientation of the object. But the physically correct rule for combining two sequential rotations, each represented as Euler angles, into a single rotation is rather complicated, and essentially amounts to converting the rotations into matrices / quaternions, multiplying them, and then converting the result back into Euler angles.)


Tuesday, August 25, 2015

c++ - Should a game clean up after itself when exiting?



Should a game/engine clean up after itself(close windows, shut down renderers, close files, free memory) when its closed?


The OS should do that anyway, and usually in a faster way.


I guess most developers don't really care as they need proper cleanup for everything anyways(With dynamic asset-loading, and changing maps, etc.), but won't ensure that everything gets cleaned perfectly.


But is there any positive to cleaning up vs not cleaning up or the reverse?



I am using C++.


What about game consoles? Do they all clean up after themselves?



Answer



Yes, a game/engine should clean up after itself when it's closed. There are good reasons for that:



  • Show to your team that you know what's going on in your game

  • Know when your managers are shut down

  • Make sure your files and handles are closed and your data is saved

  • Help prevent crashes on exit because you have a better idea to what's going on

  • Help find memory leaks: if you clean everything yourself, you should not have any memory leaks, so the next time you use a tool to detect them, it should give you 0 leaks. You'd have a harder time achieving this if you don't clean on shutdown.



And it smells fresher when stuff is clean!


2d - How to implement uniform grids


Up until now, I implemented all-against-all collision detection in my games. It worked fine.



But I reached a point where implementing this kind of collision detection, makes the game run poorly, because there are two many objects to iterate through and check for collision.


I have searched this site and found something about 'uniform grids'. But I didn't completely understand what it is and how to implement it. Tried to Google it but nothing easy enough to understand came up.


I am a beginner to 2D-game programming. Do you mind trying to explain to uniform-grids, or link me to some good tutorial?


Thanks a lot



Answer




  1. Create a 2d-array with approximately one square cell per the one collide-able object (considering the approximate max amount).

  2. Each cell in the 2d-array is a iterate-able container (data structure) of your choosing (list preferably) of collide-able objects with a bounding box that currently overlaps / intersects with that cell. It needs to be updated every frame (if the object moves).

  3. You only check for collisions between objects that are in the same cell(s) and you only check once every frame.



See the image, you would check the green ellipse against the green circle cause they are both in (1, 2).


enter image description here


web - Essential knowledge for making HTML/JavaScript-based games



I was wondering if any experts out there could share the knowledge and resources of what is necessary to start making games with the latest HTML standards and JavaScript (or what some like to call HTML 5). Are there JavaScript libraries that are essential to the process? Aside from the tag, what other pieces of HTML do we need to be aware of?




architecture - How to implement a component based system for items in a web game


Reading several other questions and answers on using a component based system to define items I want to use one for the items and spells in a web game written in PHP. I'm just stuck on the implementation.



I'm going to use a DB schema suggested in this series (part 5 describes the schema);
http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/


This means I'll have an items table with generic item properties, a table listing all of the components for an item and finally records in each component table used to make up the item.


Assuming I can select the first two together in a single query, I'm still going to do N queries for each component type. I'm kind of fine with this because I can cache the data into memcache and check there first before doing any queries. I'll need to build up the items on every request they are used in so the implementation needs to be on the lean side even if they're pulled from memcache.


But right there is where I feel confident about implementing a component system for my items ends. I figure I'd need to bring attributes and behaviors into the container from each component it uses. I'm just not sure how to do that effectively and not end up writing a lot of specialized code to deal with each component.


For example an AttackComponent might need to know how to filter targets inside of a battle context and also maybe provide an attack behavior. That same item might also have a UsableComponent which allows the item to be used and apply some effect onto a different set of targets filtered differently from the same battle context. Then not every part of an item is an active part, an AttributeBonusComponent might need to only kick in when the item is in an equipped state or when displaying the item details page.


Ultimately, how should I bring all of the components together into the container so when I use an item as a weapon I get the correct list of targets? Know when a weapon can also be used as an item? Or to apply the bonuses the item provides to a character object?


I feel like I've gone too far down the rabbit hole and I can't grasp onto the simple solution in front of me. (If that makes any sense at all.)


Likewise if I were to implement the best answer from here I feel like I'd have a lot of the same questions.
How to model multiple "uses" (e.g. weapon) for usable-inventory/object/items (e.g. katana) within a relational database




Answer



It looks like you are using relational modeling. There is an alternative method: property/prototype modeling, which Steve Yegge used to create his "ultimate extensible" MMORPG, Wyvern. Basically, each game object is stored as a single blob (only one query per object) which is then parsed into a property list after retrieval. The flexibility of property lists allows different game objects to have different sets of properties as needed.


Yegge's The Universal Design Pattern goes into depth about property/prototype modeling. Steve's blog posts tend to be quite long, so I will try to point you to the relevant sections and summarize the points relevant to your question:



  1. Wyvern uses an implementation of the Properties Pattern. A game object is basically a bag of arbitrary properties. Any object to can serve as the prototype for any other object, resulting in amazing open-ended flexibility.

  2. Persisting property lists. There are various methods of serializing and saving property lists. Wyvern uses a database, "shoving the XML-serialized property list into a text/clob column, and denormalizing the twenty or thirty fields ... needed for queries into their own columns."

  3. The datastore of property lists now needs a method of making queries on them. Steve makes several suggestions. Simple text-based queries don't work well for hierarchical data. XML databases or JavaScript/JSON + jQuery might be answers to this problem.


Monday, August 24, 2015

unity - How do I compile a C# script at runtime and attach it as a component to a game object


The idea here is to let users program the behaviour of an agent in a way that reminds of the "Screeps" game, where you get to develop code which later runs and dictates the behaviour of your units.


My idea is to let users develop the behaviour or their units with C# code, compile that code at runtime and attach it as a MonoBehavior to an existing game object.


How can I achieve this?




Answer



I haven't done this myself, so this answer is based on an article by exodrifter (I just Googled "unity runtime compile" and found 4 answers right at the top, so don't neglect to try searching yourself!)


What you're describing is possible, but not without pitfalls:




  • Use .Net 2.0 compatibility level, otherwise some namespaces you need may be absent.




  • Not every platform will allow you to compile new C# from strings at runtime - specifically Android and iOS disallow this.





  • Out of the box this works on Windows, but not on Macs/Linux unless the user has the Mono SDK installed. You can include aeroson's mcs-ICodeCompiler to build this functionality into your game as a plugin.




exodrifter's example code (modified to add a component)


(refer to the article for full details - I just want to include enough here that this answer is a useful signpost even if the linked article goes down)


using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;

using System.Text;
using UnityEngine;

public class RuntimeCompileTest : MonoBehaviour
{
void Start()
{
var assembly = Compile(@"
using UnityEngine;


public class RuntimeCompiled : MonoBehaviour
{
public static RuntimeCompiled AddYourselfTo(GameObject host)
{
return host.AddComponent();
}

void Start()
{
Debug.Log(""The runtime compiled component was successfully attached to"" + gameObject.name);

}
}");

var runtimeType = assembly.GetType("RuntimeCompiled");
var method = runtimeType.GetMethod("AddYourselfTo");
var del = (Func)
Delegate.CreateDelegate(
typeof(Func),
method
);


// We ask the compiled method to add its component to this.gameObject
var addedComponent = del.Invoke(gameObject);

// The delegate pre-bakes the reflection, so repeated calls don't
// cost us every time, as long as we keep re-using the delegate.
}

public static Assembly Compile(string source)
{

// Replace this Compiler.CSharpCodeProvider wth aeroson's version
// if you're targeting non-Windows platforms:
var provider = new CSharpCodeProvider();
var param = new CompilerParameters();

// Add ALL of the assembly references
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
param.ReferencedAssemblies.Add(assembly.Location);
}


// Or, uncomment just the assemblies you need...

// System namespace for common types like collections.
//param.ReferencedAssemblies.Add("System.dll");

// This contains methods from the Unity namespaces:
//param.ReferencedAssemblies.Add("UnityEngines.dll");

// This assembly contains runtime C# code from your Assets folders:

// (If you're using editor scripts, they may be in another assembly)
//param.ReferencedAssemblies.Add("CSharp.dll");


// Generate a dll in memory
param.GenerateExecutable = false;
param.GenerateInMemory = true;

// Compile the source
var result = provider.CompileAssemblyFromSource(param, source);


if (result.Errors.Count > 0) {
var msg = new StringBuilder();
foreach (CompilerError error in result.Errors) {
msg.AppendFormat("Error ({0}): {1}\n",
error.ErrorNumber, error.ErrorText);
}
throw new Exception(msg.ToString());
}


// Return the assembly
return result.CompiledAssembly;
}
}

Warning


Be very careful when letting your game compile & run scripts you didn't write yourself. These scripts could be made to do just about anything the player's user account has privilege to do - delete or corrupt user files, download and run malware, snoop personal information, all of that.


As much as we might try to block & detect these cases, I'd never be especially confident we'd caught them all - there's always the possibility some C# language feature I didn't know about lets them access features I thought were cut off.


If the script is only created by the local player, then they can break the game in arbitrary ways, but can't do anything to their computer they lacked permission to do anyway. But if players can share scripts, download them from a network resource, or can be tricked into copying-and-pasting a script they didn't write, then this becomes an attack vector that can be exploited.


If you want to allow programming by the player without opening up this kind of vulnerability, consider writing your own virtual machine to parse/interpret/execute the player's scripts in a more limited environment that you control completely.



phrases - Relating multiple names and values


I don't know why I have problem with saying a label:value consturction in English:


What should I write:



  • In R2, the attributes tagName and className are used to identify the main article of the web page.

  • In R2, the tagName and className attributes are used to identify the main article of the web page

  • In R2, the attributes of tagName and className are used to identify the main article of the web page





Sunday, August 23, 2015

graphics - The pros and cons - DX9 moving to DX11 render?


We are a "nano" game dev company working on REFUSION. DX9 renderer is almost done and question is: Should we move it to DX11 or not? Anyone have experience with this?


Here are some videos from dev progress from the very beginning:


Dev test videos


EDITED: I'm going to ask more fundamental. What about NextNextGen XBOX1080 or PS4?
When? Resources? Architekture? PC DX11 -12 , next XBOX, next PS relations? Future?



Answer




Regardless of your technological stance, the question should be framed in terms of your market. Are you going to be creating a game that runs on all available hardware? Or are you going to be the next Project Offset?


According to Valve DX11 capable hardware is only 5.6% of the market.


The other factors are - does your "nano" team have the bandwidth create the content and pipelines that take advantage of more recent hardware? Or are you going to be beg/borrowing/stealing art to ship something?


Note that Valve themselves support a huge range of hardware. They have a scalable engine, and the resources to do so.


EDIT: Personally, I would concentrate on shipping something that makes money as soon as possible. Yes you will need to to refactor later, even if you design your engine well.


Remember your market - they point of the game is to sell. As a compromise, I would probably target DX10 as a minimum spec. You'd get around 50% if you shipped tomorrow, and the interface is a lot cleaner than DX9. I believe, but I'm not certain, that the API difference between DX10-11 is a lot smaller than DX9-10.


pronouns - Why only "it", not "this" or "that"?




It seems you are incompetent to achieve our goal.


The chocolate tastes sweet when it is tasted. (Quasi-passive voice)


It is raining.


Your request, it is under consideration now.



and so on, so on and so on...


These constructions, if you observe, can easily understand the similarity among them- it is using "it" everytime. Now my question is why is it "it" always? Why is not this "this" or "that"?




ai - Chess Artificial intelligence with python and pygame



I created chess game with python and pygame. Now I'm trying to make Artificial intelligence, but what is actually best way to do it? Some tips, tricks, links?
Thanks




grammar - Answering a question with "Me" instead of "I" +



I heard it from a movie.


Situation 1



Mommy: Who is ready for lunch?


A boy: I am.


A little girl : Me!



Situation 2



Mommy: Who wants to eat some ice cream?



A boy: I do.


A little girl : Me!



I think "me" is an object pronoun used after a verb or preposition.


Why can we use it for answering a question?


Are there any rules about using it?


And can we use "Me!" instead of I do./ I did./ I am. / I was. and so on to answering a question starting with "Who...?" like the example below?



Mommy : Who made a mess?


A little girl : Me!



A boy : Her! (And can the boy say "Her!" which means a little girl made a mess?)




Answer



In spoken English, object pronouns are also used as emphatic or referential pronouns.


For example, I typically think of myself as "me," and a group including me as "us." We use these emphatic or referential pronouns in any stand-alone statement (i.e. one without a verb), such as a quick answer to a question.


Thus "who wants to come?" You could say in response "Me." "Us." "Not us." or "Her" or "Not us, but maybe them." (note that with "you" there is no ambiguity since the subject and object pronouns are the same.) Saying "I" or "we" or "they" or "she" is ungrammatical. Saying "I do" or "they don't" is fine but is not what most English speakers would do.


In prescriptive grammar, this is frowned upon. Hence, for instance, you can find scorepads for card games labeled "we" and "they." In my opinion this style of speech sounds very unnatural. Unless you are writing a formal document, you should aim to talk like the child in the movie, if your goal is to sound more like a native speaker.


Similarly, in response to "Who's there?" "That's me." Or when a stranger calls you on the phone and asks "Is Sarah there?" If you are Sarah, you say "that's me." (Prescriptivists will tell you to say "this is she," but this again sounds extremely formal.)


architecture - How can I design lots of different attack types that can be combined?


I'm making a top down 2D game and I want to have a lot of different attack types. I'd like to make the attacks very flexible and combine-able the way The Binding of Isaac works. Here's a list of all the collectibles in the game. To find a good example, lets look at the Spoon Bender item.




Spoon Bender gives Isaac the ability to shoot homing tears.



If you look at the "synergies" section, you'll see it can be combined with other collectibles for interesting yet intuitive effects. For example, if it combines with The Inner Eye, it "Will enable Isaac to fire multiple homing shots at once". This makes sense, because The Inner Eye



Gives Isaac a triple shot



What's a good architecture to design things like this? Here's a brute force solution:


if not spoon bender and not the inner eye then ...
if spoon bender and not the inner eye then ...

if not spoon bender and the inner eye then ...
if spoon bender and the inner eye then ...

But that will get out of hand very fast. What's a better way to design a system like this?



Answer



You totally don't need to hand-code combinations. You can instead focus on the properties that each item gives you. For instance, Item A sets Projectile=Fireball,Targetting=Homing. Item B sets FireMode=ArcShot,Count=3. The ArcShot logic is responsible for sending out Count number of Projectile items in an arc.


These two items can be combined with any other items that modify these (or other) properties freely. If you add a new type of projectile it'll just automatically work with ArcShot, and if you add a new firing mode it'll automatically work with Fireball projectiles. Likewise, Targetting is a property that sets the controller for the projectiles while FireMode creates the projectiles, so they can be easily and trivially combined in any combination as makes sense.


You might also set of property dependencies and such. For instance, ArcShot requires that you have a provider of Projectile (which might just be the default). You might set priorities so that if you have two active items that both provide Projectile the code knows which one to use. Or you can provide UI to let the user select which projectile type to use, or simply require the player to unequip high-priority items he doesn't want, or use the most recent item, etc. You can further allow a system of incompatibilities, e.g. such that two items that both just modify Projectile cannot both be equipped simultaneously.


In general, when possible, prefer any kind of data-driven approach (or declarative) over procedural approaches (the big if-else messes) when it comes to the objects and such in your game. Higher-level generic logic that is configurable by simple data is much preferable over hard-coded lists of special-cased rules.


Saturday, August 22, 2015

adjectives - The definite article before superlative degree




What are the special cases when we can't use "the" before superlative degree? I'd like the answers with proper explanations. Some of the examples:



  1. He is most likely to succeed.

  2. It is fairest of all methods.

  3. I have read many books. "Against all odds" is best of all.




animation - Is there any other way to animate 2d spritesheet without Animator Component in unity?


Is there any easy way exists that animates frames without using Animator component?



Answer



Yes, here is the basic scrip I wrote with some help of anonymous somewhere on the internet. Script contains some of his code. Well, anyone can use it. I will improve it by time.


Here is the script:


using UnityEngine;
using System.Collections;


public class AnimationScript : MonoBehaviour
{
[Header("Animate Once?")]
[Tooltip("Either animation should run once or not.")]
// Either animation should run once or not
public bool
_animateOnce = false;
[Header("Time")]
[Tooltip("Time in seconds to change frames.")]
// Time in seconds to change frames

public float
_time = 1.0f;
[Header("Sprites")]
[Tooltip("Animation sprites.")]
// Animation sprites
public Sprite[]
_sprites;

int frameCount = 0;
SpriteRenderer spriteRenderer;


void OnEnable ()
{
frameCount = 0;
spriteRenderer = GetComponent () as SpriteRenderer;
StartCoroutine ("Animate");
}

void OnDisable ()
{

frameCount = 0;
StopCoroutine ("Animate");
}

// Use this for initialization
void Start ()
{
frameCount = 0;
spriteRenderer = GetComponent () as SpriteRenderer;
StartCoroutine ("Animate");

}

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

}

IEnumerator Animate ()
{

if (frameCount >= _sprites.Length) {
if (_animateOnce) {
yield break;
} else {
frameCount = 0;
}
}
if (_sprites [frameCount] == null)
yield break;


spriteRenderer.sprite = _sprites [frameCount];
frameCount++;
yield return new WaitForSeconds (Mathf.Abs (_time));
StartCoroutine ("Animate");
}

public void StopAnimation ()
{
StopCoroutine ("Animate");
}

}

Any suggestions are always welcome.


meaning - Does "has been employed" imply they still are employed?



Mr. Smith has been employed by our company as engineer since 1st March 2015.



Does this mean Mr. Smith is still being employed by the company?





windows - Why is there a lack of games for Linux?



What is wrong with the Linux/*nix family for games? What makes the development of games for this platform too slow compared to Windows or even OS X?



Answer



For game clients, it mostly has to do with culture, leading to difficult monetization strategies.


Servers for multiplayer games, on the other hand, have gotten a lot of traction for linux/nix, it is a very attractive platform for developing server technology.



There is hope that eventual release of Steam for Linux will help change that culture when it comes to clients, and provide developers and publishers a more monetarily viable platform for distributing games.


xna - 2D graphics - why use spritesheets?


I have seen many examples of how to render sprites from a spritesheet but I havent grasped why it is the most common way of dealing with sprites in 2d games.


I have started out with 2d sprite rendering in the few demo applications I've made by dealing with each animation frame for any given sprite type as its own texture - and this collection of textures is stored in a dictionary. This seems to work for me, and suits my workflow pretty well, as I tend to make my animations as gif/mng files and then extract the frames to individual pngs.


Is there a noticeable performance advantage to rendering from a single sheet rather than from individual textures? With modern hardware that is capable of drawing millions of polygons to the screen a hundred times a second, does it even matter for my 2d games which just deal with a few dozen 50x100px rectangles?


The implementation details of loading a texture into graphics memory and displaying it in XNA seems pretty abstracted. All I know is that textures are bound to the graphics device when they are loaded, then during the game loop, the textures get rendered in batches. So it's not clear to me whether my choice affects performance.


I suspect that there are some very good reasons most 2d game developers seem to be using them, I just don't understand why.



Answer



A strong argument for using spritesheets is that the number of available textures on a graphic card can be limited. Therefore your graphics library would constantly have to remove texture and re-allocate textures on the GPU. It's much more efficient to just allocate a large texture once.



Also consider that texture sizes are usually power of 2. So if you have a 50x100px Sprite, you'll allocate textures with the size 64x128px or in the worse case 128x128px. That's just wasting graphics memory. Better pack all the sprites into a 1024x1024px texture, which would allow 20x10 sprites and you'll only lose 24 pixels horizontally and vertically. Sometimes even sprites of different sizes are combined into one huge sprite-sheet to use the texture as efficient as possible.


Addendum: A very important reason to use sprite-sheets is to reduce the amount of draw-calls on your GPU, which can have a notable impact on performance. This has been stated in other answers and I'm adding this for the sake of completeness so that this gets some more visibility.


Friday, August 21, 2015

grammaticality - How should I use "go + present participle"?


I read some activities are commonly expressed in English by "go + present participle." However, I found a sentence like "Let's go ride a bike!" and I am wondering which sentence I should use.



Yesterday, I went riding a bike.




Yesterday, I went ride a bike.






Let's go riding a bike!




Let's go ride a bike!





legal - Legality of using names in a game?


If I am creating a board-game type game, does anyone know if it is legal to use others' names in the game?


ie. A playing card with "George Bush" or "Michael Jackson" on it.



Also, is it the same for brand names?



Answer



I would say no, unless you have been given permission. For example, think of sports games that do not own the rights to the league they are covering. They end up resorting to using similar, but different names to their real life counterparts.


EDIT: I found this discussion about using sports peoples names in websites http://www.linkedin.com/answers/law-legal/property-law/LAW_PRL/566138-50912703 It seems a name itself can not be copyright (so you can use their name in a news article for instance), however if you are benefiting from using their name/image then it is a violation of publicity rights.


What is a good tool for producing animated sprites?



Has anyone come across a software package that allows you to build animations in a similar way to how you can in Flash (i.e. using techniques such as tweens & bones & easings, etc) and then have the result exported as a sprite sheet?



Answer



You can use Flash, a 3D Tool or even Photoshops animation feature. Then render the frames to images and combine them to a sprite-sheet.


ImageMagick has a great tool for that purpose called montage. Here's a blog post explaining how to use it to create a sprite sheet.



pronouns - Can I refer to an ant as "she"?


In a long text about a foraging ant, would it be correct to refer to the ant always as "she" instead of "it"? For example,



She wanders aimlessly until she finds a pheromone trail.



A foraging ant is always a female, so technically it would be correct. However, wouldn't that seem odd to the layperson?


The ant in question is not anthropomorphized at all.




Answer



Here is an excerpt from The Ants, the monumental, 732-page reference on every major topic in the scientific study of ants, by Bert Hölldobler and E.O. Wilson, two of the world's leading authorities on ants:



The Epiritus forager hunts a great deal in small crevices within the soil. Because of the tightness of the passages, she usually encounters the prey in front. The ant immediately crouches and freezes, pulling the antennae completely back into the scrobes that line the sides of her head. The mandibles remain closed. Even though the prey (a collembolan or small centipede) may be very close by, the ant never moves toward it. Instead, she remains perfectly still for periods of 20 minutes or longer, waiting for the prey to step on her head. Then, with a sudden upward snap of her mandibles, she impales the victim on the long apical teeth. [p. 565]



In formal settings, it is perfectly normal and expected to use the pronouns he, she, her, and him to refer to non-human animals when their gender is known. No anthropomorphism is implied.


See also the Chicago Manual of Style.


architecture - Tips for Component Based Entity System message handling


I'm trying to implement a component-based entity system but am a bit confused on how I should handle the messaging. There are two problems I'd like to resolve so I can test the system. Below is the code I have so far,


The Entity class:


class Entity{

public:
Entity(unsigned int id):
id_(id)
{};
void handleMessage(BaseMessage &message){
for(auto element: components_){
element.second->handleMessage(message);
}
}
template

void attachComponent(T *component){
//Consider making safer in case someone tries to attach same component type twice
components_[typeid(T).hash_code()] = component;
}
template
void detachComponent(void){
components_.erase(typeid(T).hash_code());
}
template
T* getComponent(void)const{

return *components_.find(typeid(T).hash_code());
}
unsigned int getInstanceID(void)const{
return id_;
}
private:
unsigned int id_;
std::map components_;
};


The Base Component and Message classes:


class BaseComponent{
public:
virtual void handleMessage(BaseMessage &message){};
};

class BaseMessage{
public:
virtual int getType(void) = 0;
};


1. Message Type Handling


My first question is how I should handle the different (derived from BaseMessage) message types.


I have thought of two ways for handling the message types of the derived message types. One is to generate a hash (i.e. using FNV) from a string that names the message type and use that hash to determine the message type. So the handleMessage(BaseMessage &message) function, would first extract this hash from the message and then do a static_cast to the appropriate type.


The second method is to use a template as follows (similar to the attachComponent methods of the entity class),


template
handleMessage(T& message){};

and make specializations for each message type the specific component is going to make.


Are there any drawbacks using the second method? What about performance-wise, why don't I see this kind of use more often?



2. Input Handling


My second question is what would be the optimal (in terms of latency and ease of use) way to handle input?


My thought was to create an InputHandlerComponent which registers with the keyboard class to listen to specific key presses defined possibly in some file. For example


keyboard.register( player.getComponent() , 'W')

I wish there was a more concise guide to component based systems but I guess there are many different ways to do the same things. I have more questions but I think it'd be wiser to first try implementing what I can.



Answer



In a typical entity system you leave systems to have all the logic for your game and components to store data only, and your entities are just a simple identifier. Input handling would be much easier that way and not to mention the flexibility of your game.


There are plenty of ways to handle events, such as: the observer pattern, or signals/slots. You could do message handling with templates/virtual functions or function pointers, however it'd probably be easier to use boost::signals, even known it's not that great for performance. If you want performance*, I suggest you use templates and virtual functions or function pointers.


*I noticed that your code could really be optimised. There are alternatives to the typeid operator, which are actually faster than using typeid. Such as using templates/macros and simple integers to define a class's ID.



You can look at my Entity System if you need some inspiration (which is inspired from the Java framework Artemis). Although I haven't implemented a way to handle events (other than entity-related events), I left that up to the user, but after sussing out the entityx library, which I found on reddit. I figured I might be able to add an event system to my library. Please do note that my entity system isn't 100% complete on what features I want, but it works and has decent performance (but I could optimize, especially with the way I'm storing entities).


Here's what you could possibly do to handle events (inspired from entityx):


BaseReceiver/BaseListener



  • A base class so you may store listeners/receivers.


Receiver/Listener



  • This is a template class and requires you to override the virtual function recieve(const T&), where T is event information.

  • Classes that want to be notified by events that send specific information when an event occurs must inherit from this class.



EventHandler



  • Emits/fires events

  • Has a list of Receivers/Listeners objects that will be notified by fired events


I've implement this design in C++, just now, without the use of boost::signals. You can see it here.


Pros



  • Statically typed


  • Virtual functions (faster than boost::signals, well it should be)

  • Compile-time errors if you didn't emit notifications correctly

  • C++98 compatible (I believe)


Cons



  • Requires you to define functors (you can't handle events in a global function)

  • No event queue; just register & fire away. (which may be not what you want)

  • Not direct calls (shouldn't be that bad for events)

  • No multiple event handling on the same class (this could be modified so it does allow multiple events, via multiple inheritance, but may take some time to implement)



Also, I have an example in my entity system, which does deal with rendering and input handling, it's quite simple but it presents many concepts to understand my library.


physics - When should I use a fixed or variable time step?


Should a game loop be based on fixed or variable time steps? Is one always superior, or does the right choice vary by game?




Physics updates are passed a "time elapsed since last update" argument and are hence framerate-dependent. This may mean doing calculations as position += distancePerSecond * timeElapsed.


Pros: smooth, easier to to code
Cons: non-deterministic, unpredictable at very small or large steps


deWiTTERS example:


while( game_is_running ) {
prev_frame_tick = curr_frame_tick;
curr_frame_tick = GetTickCount();
update( curr_frame_tick - prev_frame_tick );
render();
}



Updates might not even accept a "time elapsed", as they assume each update is for a fixed time period. Calculations may be done as position += distancePerUpdate. The example includes an interpolation during render.


Pros: predictable, deterministic (easier to network sync?), clearer calculation code
Cons: not synced to monitor v-sync (causes jittery graphics unless you interpolate), limited max frame rate (unless you interpolate), hard to work within frameworks that assume variable time steps (like Pyglet or Flixel)


deWiTTERS example:


while( game_is_running ) {
while( GetTickCount() > next_game_tick ) {
update();
next_game_tick += SKIP_TICKS;

}
interpolation = float( GetTickCount() + SKIP_TICKS - next_game_tick )
/ float( SKIP_TICKS );
render( interpolation );
}





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...