Wednesday, October 31, 2018

sentence construction - The giraffe ear is fell off




"The giraffe ear is fell off."



my son told me.


One of the ear of giraffe wall sticker is fell off.


What do we say for this? The rest (giraffe's body) is still sticking on the wall.


Only part of its ear is dropping.


Picture of a giraffe wall sticker



Answer




The giraffe's ear is falling off.




or



The giraffe's ear has fallen off.



You can also say:



The giraffe's ear is coming off.



or




The giraffe's ear has come off.



To be accurate, you wouldn't say something has fallen off (or come off) unless it was completely separated from whatever it was attached to. But kids are not always as precise with their language.


(Edit): Also (as per BruceWayne's comment)



The giraffe's ear fell off.


The giraffe's ear came off.



Architecture a for a central renderer rather than self-rendering




For the architectural side of rendering, there's two main ways: having each object render itself, and having a single renderer which renders everything.


I'm currently aiming for the second idea, for the following reasons:




  • The list can be sorted to only use shaders once. Else each object would have to bind the shader, because it's not sure if it's active. The objects could be sorted and grouped.




  • Easier to swap APIs. With a few macro lines, it can be easy to swap between a DirectX renderer and an OpenGL renderer (not a reason for my project, but still a good point)




  • Easier to manage rendering code


Of course, if anyone has strong recommendations for the first method, I will listen to them.


But I was wondering how make this work.


First idea
The renderer has a list of pointers to the renderable components of each entity, which register themselves on RenderCompoent creation. However, I'm worrying that this may end up as a lot of extra pointer weight. But I can sort the list of pointers every so often.


Second idea
The entire list of entities is passed to the renderer each render call. The renderer then sorts the list (each call, or maybe once?) and gets what it wants. That's a lot of passing and/or sorting, however.


Other ideas
???

PROFIT


Anyone got ideas? Thank you.



Answer



Third idea


Each entity submits an encoded integer key, possibly with an associated value to the renderer for each item to be rendered. The renderer can then sort the keys using any fast integer sorting method, and submit each item to be rendered.


By encoding the key in the order you want each component sorted, from MSB to LSB, you get the benefits of your second idea with a much faster sorting step.


There's a huge amount of flexibility here in terms of how you encode your key, from something as minimal as:


|MaterialID|Depth|MeshID|
| 4| 20| 8| (16 materials, 256 models)


To a more complex 64-bit key & pointer value:


|Fullscreen|Viewport|Layer|Blend|Depth|MaterialID|  :  ptr_to_data
| 2| 3| 3| 2| 23| 30|

There are several additional benefits to using integer keys; for example, if you have a static section of the scene you can cache the resulting keys and simply re-submit the prepared list (if used often, pre-sort and use a suitable sorting algorithm).


sentence meaning - What does "a satisfactory conclusion the UN Security Councilˈs consideration of this matter" mean?



There would be additional steps in between the initial measures and the final step, including, among other things, addressing the UN Security Council resolutions, with a view toward bringing to a satisfactory conclusion the UN Security Councilˈs consideration of this matter.



For context: here


1)Is there any redundancy in "including, among other things"?


2)This part seems a bit odd: with a view toward bringing to a satisfactory conclusion the UN Security Councilˈs consideration of this matter. What is the apostrophe s contradiction for?



Answer




The confusion seems to be a result of a heavy NP shift (heavy noun phrase shift).


Consider:



with a view toward bringing it to a conclusion.
with a view toward bringing to a conclusion it.*
* denotes incorrect usage



We wouldn't move it to the end of the sentence because it is too light. However, in our sentence we instead have the UN Security Council's consideration of this matter, which is a heavy NP (noun phrase), so it can be shifted to the end.



with a view toward bringing to [a satisfactory conclusion] [the UN Security Council's consideration of this matter].




It might be easier to understand the phrase by moving the heavy NP back:



with a view toward bringing [the UN Security Council's consideration of this matter] to [a satisfactory conclusion].



With that, it should be easy to see that this heavy NP is simply the "Council's consideration", where "Council" means the UN Security Council, and the "consideration" means the consideration of this matter, and it's the Council's consideration.


The part "addressing the UN Security Council resolutions, with a view toward bringing to a satisfactory conclusion the UN Security Councilˈs consideration of this matter" would refer to such addressing and it means that the addressing would be done with a view toward bringing the Council's consideration to a satisfactory conclusion.




As for whether including, among other things is redundant or not, I would say that it can be considered redundant; however, in my opinion, if we removed the among other things part, the addressing would appear to be less important than it currently is, as it appears in the original sentence.


unity - Why is Raycast hitting masked layer?


Many questions have been posted on this topic but I'm facing a weird behavior which I could not find an explaination for.


I perform a raycast giving it a LayerMask parameter which is defined as public variable and set in the inspector with thick on layer "Wall" and "Enemy".


At first glance it appeared to work fine because raycast rightly stops on GameObjects with that layer.


But then I saw that it stopped also on GameObjects with default layer, like if the LayerMask was ignored. Is there something I'm missing?



According to this answer I set up everything correctly and I expected it to work fine.


Looking at the inspector at Runtime I can clearly see that my mask is set only to "Wall" and "Enemy", and that the GameObject the collider is attached to has default layer set. I'm then stating that the mask the way I'm using it does not exclude other layers. The only way I found to have this working is by setting that GameObject layer to Ignore Raycast but in this case the LayerMask is not necessary.


I'm calling the function this way:


RaycastHit2D inSight = Physics2D.Raycast(start, end, lm); 

Maybe is there something different using Physics2D?
I would really enjoy touse LayerMasks instead of giving specifically Ignore Raycast to whatever I want to ignore. Any clue?



Answer



I've had this happen with the 3D raycast in the past, and it seems to be because the raycast functions have so darned many optional parameters, and LayerMasks aren't picky about what type they're treated as.


From the docs:



public static RaycastHit2D Raycast(
Vector2 origin,
Vector2 direction,
float distance = Mathf.Infinity,
int layerMask = DefaultRaycastLayers,
float minDepth = -Mathf.Infinity,
float maxDepth = Mathf.Infinity
);

layerMask is the fourth parameter. So if you provide only three parameters, Unity wants to interpret them as origin, direction, and distance.



It might seem like providing an input of type LayerMask should make your intent unambiguous, or at least generate a compile-time error, but LayerMask can implicitly convert to int, and int can implicitly convert to float.


So when you put a LayerMask in the third argument, the compiler tries to convert it to a float, succeeds, and so silently re-interprets your mask as a distance. The fourth parameter layerMask is then unspecified, so it defaults to DefaultRaycastLayers, basically ignoring the layers you chose in the Inspector.


You can fix this by providing a dummy distance value (say, infinity, if you don't have any more conservative upper bound) so your layer mask selections end up in the fourth argument where Unity expects it:


RaycastHit2D inSight = Physics2D.Raycast(start, end, float.PositiveInfinity, lm);


Tuesday, October 30, 2018

word usage - What's the difference between "center" and "centre"?



Which one is correct: examination center or examination centre? What is the difference between center and centre? Is the difference only in spelling? What is the usage difference?



Answer



Originally, everyone spelled it centre, but because of Noah Webster's spelling reforms, people in the US started spelling it center, particularly in the last century. Although the revised spelling center has been adopted internationally to varying extents, centre is still more popular in most regions. But regardless of how you spell it, it's the same word, so it has the same meaning either way.


To get a clearer picture of which spellings are used in which countries, I turned to the Corpus of Global Web-Based English (GloWbE). After searching for both terms, I took the raw data and created a chart of percentages using the formula center / (center + centre), which I sorted in descending order. Here's what I found:


Percent of the time center is used rather than centre, by region


  United States 92.2%
Philippines 87.5%
Pakistan 54.0%
Hong Kong 51.8%
Bangladesh 51.2%

India 43.8%
Tanzania 42.5%
Singapore 40.7%
Kenya 40.3%
Jamaica 40.3%
Nigeria 39.1%
Malaysia 35.1%
Ghana 34.4%
Sri Lanka 33.8%
Canada 33.0%

New Zealand 24.2%
Ireland 20.1%
South Africa 19.8%
Great Britain 19.4%
Australia 18.1%

As you can see, center is more popular in the US, while centre is more popular in the UK. Many regions fall closer to the center of the spectrum, with India favoring centre only somewhat, and Hong Kong using both spellings in roughly equal proportions. Overall, centre is more popular in international English.


Which should you use? Well, if you're required to follow a style guide, use whichever spelling it suggests. If you have a choice, and you're writing in a region like the US or UK that strongly prefers one spelling, I suggest you use that spelling. (I don't think either spelling is ever "incorrect", but it's possible that the person grading your test might disagree with me!) Otherwise, you can spell it however you like.


Finally, I'd like to add one note about the percentages above. The tendencies at the top and bottom ends of the chart are likely to be stronger than the percentages indicate, primarily because spellings are usually respected in proper nouns regardless of region. If you talk about the Capital Centre, for example, you're likely to spell the word centre rather than center regardless of which region you're in. But since most uses of this word are not in proper nouns, the percentages should be roughly accurate, particularly toward the center of the list; it should be enough for you to decide how to spell the word.


publishing - How is money made from Steam Trading Card Farming Generators?


in this SidAlpha Video, SidAlpha talks about how Valve may be doing something that could stop or interrupt Steam Trading Card Farming Generators by preventing them from generating keys.


This got me thinking. from my understanding you get Trading Cards either playing the game which gets you only so many, the rest you then need to create booster packs with Gems or buy them from the marketplace with your own funds. but what i don't get is


1) the name for this practice implies using Steam Trading Cards to make money, however i can't see how "developers" can make money as,



  • you have to originally own the card you're selling on the market place

  • when it's brought it goes to your wallet which you can't transfer Steam wallet fund off Steam



and i wouldn't think Valve would allow "developers" to create any number of trading cards for their games at will then sell them because this is obviously very easily abused


2) in the video SidAlpha mentions that reducing/blocking Key generation may have an impact to those who use Steam Trading Card Farming Generators, noting that a certain user base is actually worried it. but i'm not sure how key generation fits in to the scam.


So my question is how is money made from Steam Trading Card Farming Generators? and how do Steam Keys fit in to this?




Monday, October 29, 2018

Optimizing an XNA 2D game


Does it make sense to implement the logic to skip rendering objects outside the viewport or should I not care about it and let the Framework do it?



Answer



Culling is a performance optimisation. So it doesn't make sense to just do it just for the sake of it. You have to have a reason.




The GPU (not the XNA Framework) culls triangles and pixels at blindingly fast speed. Every triangle you submit must be transformed (via your vertex shader). Then it culls the ones that land off screen. Then it fills the remaining triangles, culling pixels that are off-screen. The remaining pixels are then drawn to the back buffer (via your pixel shader).



(When I say "then" - it actually does all this in a massively parallel pipeline.)


So it's very rare and unusual that you might have to cull individual triangles. To hit vertex limits you have to be drawing an absurdly large number of triangles. To hit fill-rate, texture-fetch or pixel-shading limits, you generally need to have a high depth-complexity (in which case viewport/frustum culling will not help).




So there's usually little or no cost to having geometry off-screen.


The cost - particularly in the context of drawing "objects" (usually 3D objects) - is actually in submitting those objects to the GPU in the first place. Submit too many objects and you hit your batch limit (you get a few thousand* batches per frame).


I recommend reading this answer and this linked slide deck for an in depth description of batches.


Because of this, if you implement frustum culling, you can reduce the number of batches you submit to the GPU. If you're batch limited - this can get you under the limit.




Now - your question is about 2D XNA - so presumably you are using SpriteBatch. This is a bit different.


It is no mistake that it is called "Sprite Batch". What it is doing is taking the sprites you draw and doing the best it can to submit those sprites to the GPU in as few batches as possible by batching them together.



But SpriteBatch will be forced to start a new batch if:



  • You draw more sprites than it can fit into a single batch (2048 sprites in XNA 4)

  • You change texture (this is why there is a sort-by-texture option)


So culling is a suitable optimisation if you are running into the first one. If you are sending such a huge number of sprites that you end up with too many batches (you're probably using up bandwidth as well - but I'm pretty sure you'll hit the batch limit first). This will generally only happen if you have a truly enormous world - so you can generally get away with very simplistic, fast-but-inaccurate culling in this case.


Now - If you are drawing with enough texture-swaps to take you over the batch limit, and lots of them are actually off-screen and culling them would get you under the batch limit. Then yes - culling is an optimisation that will work.


However - a better optimisation to pursue in this case is to use texture atlases (aka: sprite sheets). This allows you to reduce the number of texture-swaps and therefore batches - regardless of what is on screen or off. (This is the main reason you can specify a source rectangle for your sprites.)




(As always: this is advice on performance optimisation. So you should measure and understand your game's own performance, and what limits you are hitting, before spending effort on adding optimisations.)



xna - Building a chunk w/ blocks: making ramps. How to detect if blocks are making "stairs" (like in a mountain) and should be turned into ramps?


My question is quite simple, but the answer may be not.


I am studying and making a voxel engine, generating block vertices around its center position with TriangleList primitive at C#/XNA.


The problem is that I don't want that my game make those ugly "stairs" of cubes in mountains or hills. I want that the cube turns into a ramp when needed (when it has no connection with blocks at some sides, for example: no connection at top and east, then it turns into a ramp from west top to east bottom).


Another example that already exists may be found at SimCity 2000 maps. Edges become ramps, in many types, depending of how the squares of the terrain grid are modeled. Even corners between two directions of ramps become a new type of ramp, with two triangles.


I don't know how to detect that in a easy way, like, do I have to test each side and then check between the sides detected for selecting the type of ramp to create?... Or what should I test first, and then select the way of placing the vertices?


Thanks for any answer. And sorry for my English, if something is wrong.



Answer



As far as I know, there's no existing algorithm for this, you'll just have to create one. You're already on the right track. For each cube, check the surrounding cubes to see if converting the current cube is reasonable.


For example, say we're looking at cube #5 on a hill side. (green is solid, while is air).



enter image description here


This image will represent the X axis. You'd perform this test for the Z axis as well. Basically, we can simplify the check to:


if(isSolid(x-1, y, z) && !isSolid(x+1, y, z))
ConvertToRamp(x, y, z, RampDirection.TopWest);
else if (!isSolid(x-1, y, z) && isSolid(x+1, y, z))
ConvertToRamp(x, y, z, RampDirection.TopEast);

In this case, we'll trigger the second option, because 4 (x-1) is not solid, and 6 (x+1) is solid. This will convert 5 into a ramp with its top toward the East (top in the X plus direction), as shown with the red line.


The same check can be performed for the z axis. Then you'll find that you have a case where a ramp is valid in two directions. You can either choose a direction to make the ramp, or create some kind of dual direction ramp.


So what about performance? Running this check on every cube might get crazy when generating terrain. There's a few things you can do:




  • Only check surface level cubes. Don't worry about making ramps underground.

  • Don't perform this test on cubes that are air.

    • Or only perform it on cubes that are air with solid cubes below them. This would add new ramps to your existing blocky terrain.



  • Store a byte for each cube that describes if its neighbors are solid or not (for example, a 1 for solid and 0 for air). Then you can do a quick bit check to test if a cube should be a ramp. This sort of offsets the performance hit to another stage of world generation, but it's likely a stage the user is either expecting (loading screen) or they're not watching and waiting for it to happen (chunk generation out of view).


word usage - Can I say "do some recreation"?


Here is to check out if it is okay to say "do some recreation" to mean "do some leisure activities"?


The original sentences is "Doing some recreation during the leisure time is good for us."




Sunday, October 28, 2018

conjunctions - Should I write "X and I", "X and me", "I and X", or "me and X" in a conjoined object?


A question was asked in one of my friend's interview. The question was to determine the right form from the below sentences.



Q. Correct form of English:



  1. Samuel was with Susan and I

  2. Samuel was with Susan and me

  3. Samuel was with I and Susan


  4. Samuel was with me and Susan

  5. None of these



Now I vaguely remember a rule of thumb from my school days. That is "2-3-1" i.e. where all the persons are acting in a sentence, second person comes first, then third person and it is followed by first person.


So according to this theory, 1 seems to be correct to me. Is this theory correct?



Answer



Your theory is correct. But that leaves us with 1) and 2).


Between I and me, we can decide like this: I corresponds to we and me corresponds to us. 'He was with us' and not 'He was with we.' So, 2) is the correct option.


grammar - Confusion about the use of 'quite' in 'quite a bit', 'quite a few', and 'quite a lot'



I have a hard time understanding some definitions and usage of quite in English Grammar Today (via Cambridge Dictionaries Online). The explanation is as follows:



Quite a bit, quite a few, quite a lot


We often use quite with a bit, a few and a lot to refer to large amounts and quantities:


You should ask Mez for some advice. He knows quite a bit about gardening.



(I don't know if he knows a lot or a little about gardening, because of a bit is used here.)



A: We bought quite a lot of new furniture, didn’t we?
B: Yeah, quite a bit.




(Do quite a lot and quite a bit suggest the same meaning? Does quite a bit mean "very little"?)



There were quite a few of us at the meeting.



(What does quite a few mean? Does it mean "very little"?)



We also use quite a bit and quite a lot to mean ‘often’:


Do you come here quite a bit?




(Do quite a bit, quite a lot, and quit a few have the same meaning in this context? If Not, why?)



I used to go sailing quite a lot.



(Can we use quite a bit or quite a few here without changing the meaning of this sentence?)





Quite + a lot /a bit + comparatives



We often use quite a lot and quite a bit with a comparative adjective or adverb to mean ‘much’:




We went to Italy when I was quite a bit younger.



(Can we use quite a lot or quite a few here without changing the meaning of the sentence?)



The new truck is quite a lot heavier than the old model.



(Can we use quite a bit and quite a few here without changing the meaning of sentence?)




Is 'where' used as a pronoun in relative clauses?


Please take a look at the following examples:





  1. (a) Statement: He works in a office.
    (b) Relative clause:
      1. The office where he works (is for rent).
      2. The office in which he works (is for rent).


    Here, 'where' = 'in which', and I think 'where' is used as an adverb to mean 'in, on, at or to which' in relative clauses.




  2. (a) Statement: He works near the office.

    (b) Relative clause: The office near where he works.


    I think here 'where' = 'the office'.




My questions:



  1. Is 'where' used as a pronoun? (as 2.(b))


  2. Can we use other prepositions of places (except 'in, on, at, to') with 'where' as 2.(b)?


    For example:



      1. The bridge under where we live...
      2. The beach behind where i am standing...
      3. The shop next to (close to/before/opposite/in front of, etc.) where we live





Answer



Where is a ‘pro-form’—it ‘stands for’ or refers to another entity in the discourse—but it is not a pronoun. It should be understood as a ‘pro-adverbial: it stands for an adverb, or for a clause or preposition phrase which acts as an adverb.


Because where does not stand for a noun or noun phrase, it cannot act as the object of a preposition:



The office in where I work is on the fourth floor.




If you want to refer to the place itself in a preposition phrase you must use which:



ok The office in which I work is on the fourth floor.



HOWEVER: this does not mean that the three examples in your question are ungrammatical; they are grammatical, but they do not mean what you want them to mean.


Just like pronoun wh- forms, where can be used to head an interrogative:



Where do you work? —I work at 1801 Broadway.




Where can also head a bound relative clause:



I work at 1801 Broadway, where my office is on the fourth floor.



Here where is equivalent to in or at which place.



  • Note, by the way, that in such clauses where may also have the extended sense of at the place where:

    I work on Broadway, where it intersects with Washington.






Where can also be used to head a fused relative clause; and this is where it gets tricky. In this sort of clause the wh- form does not stand for another entity but designates a ‘variable’ whose referent is not specified: in effect, the wh- form is its own referent! A fused relative clause acts as an NP (nominal); for instance, it may be the subject or object of a verb:

Where I work is my office on Broadway.
I will tell him where I work, and he can meet me there.



And the clause—not where itself, but the entire clause it heads—may also act as the object of a preposition:



The bus stops three blocks from where I work.




That is what is involved in your three examples. As you will see from the paraphrases, they signify something quite different from what you intend:




  1. The bridge under where we live... This does not mean that you live under the bridge, but that the bridge is under the place where you live: apparently you live over the bridge! What you mean is The bridge under which we live ...

  2. The beach behind where I am standing... This does not mean that you are standing behind the beach, but that the beach is behind the place where you are standing: apparently you are standing in the water looking out to sea! What you mean is The beach behind which I am standing...

  3. The shop {next to/close to/before/opposite/in front of, etc} where we live... These are not all so absurd as the previous examples, because the spatial relationships are in most cases reciprocal: if the place where you live is ‘opposite’ the shop, the shop is also ‘opposite’ the place where you live. Still, before and in front of inverts the spatial relationship; and in all these cases, you are inverting your topic: instead of a bound relative clause describing where you live relative to the shop, you have a fused relative clause describing where the shop is, relative to where you live.






  • NOTE: It is true that in casual speech (and in writing which reflects casual speech) where often ends up with the sense of a pronoun; Man_From_India cites



    Where's your favorite destination?



    In speech, people often start sentences pointing in one direction, and then end them somewhere else. That’s ordinary and inevitable, because they’re assembling their thoughts on the fly. Hearers allow for that imprecision because they’re parsing the same way; and as long as the rough sense is clear nobody worries much about the syntactic details. Noncasual writing, however, demands strict precision, because there’s no opportunity for the writer and reader to clear up any ambiguity or misunderstanding which may arise. My answer above addresses the precise use of where in noncasual writing, which would require



    What is your favorite destination?








marks a usage as unacceptable


architecture - Event-driven Communication in a Game Engine: Yes or No?


I am reading Game Coding Complete and the author recommends Event Driven communication among game objects and modules.


Basically, all living game actors should communicate with the key modules (Physics, AI, Game Logic, Game View, etc.) via an internal event messaging system. This means having to design an efficient event manager. A badly designed system eats CPU cycles, especially affecting mobile platforms.


Is this a proven and recommended approach? How should I decide whether to use it?



Answer



This is an expansion of my comment to a full answer, as suggested.


Yes, plain and simple. Communication needs to happen and while there are situations where 'Are we there yet?'-type polling is required, having things check to see if they should be doing something else generally wastes time. You could instead have them react to things they are told to do. Plus, a well defined communication pathway between objects/systems/modules boosts parallel setups significantly.


I've given a high-level overview of an event messaging system over on Stack Overflow. I have used it from school into professional gaming titles and now non-gaming products, adapted to the use case every time of course.


EDIT: To address a comment question on how do you know which objects should get the message: The objects themselves should Request to be notified about events. Your EventMessagingSystem (EMS) will need a Register(int iEventId, IEventMessagingSystem * pOjbect, (EMSCallback)fpMethodToUseForACallback) as well as a matching Unregister (making a unique entry for an iEventId out of the object pointer and callback). This way, when an object wants to know about a message it can Register() with the system. When it no longer needs to know about the events, it can Unregister(). Clearly, you'd want a pool of these callback registration objects and an effective way to add/remove them from lists. (I've usually used self ordering arrays; a fancy way of saying they track their own allocations between a pool stack of unused objects and arrays that shift their sizes in place when needed).



EDIT: For a completely working game with an update loop and an event messaging system, you might want to check out an old school project of mine. The Stack Overflow post linked above also refers to it.


unity - How does a game like Enter the Gungeon handle forward and backwards movement with their orthographic set up?


So I've been scratching my head at this problem for over a week now, and would love some insight from anyone who might know a bit more.


In my game I have the floor flat on the X/Z plane with walls/characters rotated +45 degrees about the X axis. The orthographic camera is pointing down also at 45 degrees about the x axis, parallel with my walls/characters: enter image description here


As a result, I dont see any distortion for players/characters since they face the camera directly on, while the ground however sees a distortion of sqrt(2) shorter. This makes sense considering how an orthographic camera works. To fix this, I've made my Tilemap set up with X:1 Y:1 Z:Sqrt(2) so that each tile is stretched on the Z axis by Sqrt(2) to compensate for this distortion.


All looks well with only one problem now... foreshortening with regards to movement: Forward and backwards movements of objects/characters along the z axis are perceived to be slower than movements left/right on the x axis. This makes sense because while each tile is perceived to be a square in the camera view thanks to scaling Z on the tilemap by sqrt(2), the real world tile is, well, sqrt(2) times taller than its width, so obviously it takes longer to travel forwards / backwards.


I've found another post here that also touches on this: How to handle forward/backward movement in an oblique top-down view


Now looking at this thread: https://www.reddit.com/r/EnterTheGungeon/comments/4sed7a/developers_how_did_you_get_into_programming_and/d7p3jjv/?utm_source=share&utm_medium=web2x


It seems to me that DodgeRollBrent is describing almost an identical setup in their game, Enter the Gungeon, with the minor exception that their camera is facing directly along the z axis and the floor and walls are rotated +45/-45 instead. And yes they choose to also scale their walls/characters by sqrt(2) as they're parallel with the floor.


I think the part where I'm particularly confused is where the user HubT initially asks:




I mean if I create an orthographic camera and tilt it by 45 degrees the sqrt(2) distorted walls (the walls have Z depth and are perpendicular to the ground) align up nicely but the ground gets distorted (obviously). So I distort the ground tiles by sqrt(2) but this essentially stretches the ground by 40% so every vertical movement now has to be increased by 40%.



And DodgeRollBrent responds with:



so the walls are tilted 45 degrees toward the camera, and the floors are tilted 45 degrees away from the camera, meaning that each should experience sqrt(2) distortion because of the additional length along the z-axis


however, the vertical (y-axis) floor length shouldn't be perceptually changed. i think it sounds like the element you're missing is that the ground is tilted with respect to the camera as well.



So it looks like indeed their camera is facing the floor at an angle, but from what they've described they don't seem to be having the foreshortening problem that both me and the other user have described (movement being slowed down by ~40%).


My summed up question:


What does he mean by:




the vertical (y-axis) floor length shouldn't be perceptually changed.



This seems to contradict what they say about the 45 degree angled floor / both the floor/walls being distorted by sqrt(2).


I would love someone else's interpretation of all this. If I have an orthographic camera facing the floor at an angle as I've pictured above, are my only two options to fix foreshortened movement (based on the other question on gamedev stack exchange linked above) to either:




  1. Amend vertical movement to be faster (would it be as simple as setting the z component of the velocity to be sqrt(2) times faster?)





  2. Set up my camera to be "Oblique" with a scale set to the z - axis (As mentioned here: How to handle forward/backward movement in an oblique top-down view)




Or is there another way of solving this? I'm very wary of changing the vertical speed as I can very well see some knockons of this in the other systems of my game.


I'm also a bit worried about messing around with the projection matrix. Just from testing using this script provided here: https://github.com/keijiro/unity-oblique-projection I'm having some confusion understanding what the z scale should be in my case, and also why the camera seems to get offset when I set the z scale (although I'll save these questions maybe for another post since this one is plenty long now).


If you've read through this, thank you. Any help with this would be massively appreciated.




Saturday, October 27, 2018

python - How to march tiles together like in Terraria?


I've been trying to get tile marching to work like in Terraria, and I got something to work. I don't think it's actually very good way of doing this, so I'm wondering what would be really the main way of doing this.


Here's a picture of what I want to accomplish:


Tiles


As you can see, this really does the thing that I want, but it's so horrible looking and it'd be a pain to extend for different types of tiles.


Here is my code for this. I coded this as a test, so my full game would use tile classes etc.


for x, tile in enumerate(row):
if tile:

try:
air = row[x + 1]
except Exception:
pass
else:
if not air:
if not LEVEL[y - 1][x]:
tile = 3
else:
tile = 6

air = row[x - 1]
if not air:
if not LEVEL[y - 1][x]:
if tile == 3:
tile = 5
else:
tile = 4
else:
if tile == 6:
tile = 8

else:
tile = 7
LEVEL[y][x] = tile
for y, row in enumerate(LEVEL):
for x, tile in enumerate(row):
if LEVEL[y - 1][x] in (6, 3, 14):
try:
pos = LEVEL[y][x + 1]
except Exception as e:
print(e)

else:
if pos in (2, 3):
LEVEL[y][x] = 11
if LEVEL[y - 1][x] in (7, 4, 15):
pos = LEVEL[y][x - 1]
if pos in (2, 4):
LEVEL[y][x] = 12
if LEVEL[y - 1][x] in (5, 8):
if LEVEL[y][x] == 1:
LEVEL[y][x] = 13

if LEVEL[y][x] == 6:
if LEVEL[y][x - 1] in (2, 4):
LEVEL[y][x] = 14
if LEVEL[y][x] == 7:
try:
tile = LEVEL[y][x + 1]
except Exception as e:
print(e)
if tile in (2, 3):
LEVEL[y][x] = 15


The basic idea behind this is just to look for some air and dirt, and set the tiles image from those.


Basically then when I'm drawing this I just take the value at a coord and blit the corresponding image to the screen.


So how would I go about making this as readable and easily extendable as possible? Does anyone know how Terraria handles this?



Answer



If I understand right, your map stores whether something is dirt or air, and the simplest thing would be to have dirt and air tiles. However, to make things look better, you have separate images for air above dirt, dirt above air, dirt left of air, and so on. So you're trying to figure out which image to use, given a tile and its neighbors. Is that right?


If so, take a look at one of these articles:



verbs - If he were Or If he was


I saw this New York Times article:



Mr. Trump’s presence in the 2016 race has already had pernicious effects, but they’re nothing compared with what would happen if he were the Republican standard-bearer. The nominee, after all, is the leader of the party; he gives it shape and definition.



According to normal grammar rules, one should write "he is", "he was", "they are", and "they were". So, in the article above, is "he were" wrong? Should "he were" be changed to "he was"?




software engineering - Are there cases where globals/singletons are useful in game development?



I know that having global variables or singleton classes creates cases that can be difficult to test/manage and I have been busted in using those patterns in code but often times you gotta ship.


So are there cases where global variables or singletons are actually useful in game development?




Pronoun use with preposition: "with *he* and his wife" or "with *him* and his wife"?


This sentence was in a newspaper article: "Eddie smiled as Will talked with he and his wife."


I feel it means "Eddie smiled as Will talked (with him) and (with his wife)."


So it should be "Eddie smiled as Will talked with him and his wife.


Which one is correct?





gerunds - "prefer ~ing" / "prefer to infinitive"


I know I can use "prefer to infinitive" and "prefer ~ing".


And when I use "prefer ~ing", we use "to" to compare.




  1. I prefer studying at a coffee shop to studying in the library.



Then, how about "prefer to infinitive"?





  1. I prefer to study at a coffee shop to to study in the library.



I think it sounds not correct. rather I would use like this:


I prefer to study at a coffee shop rather than studying in the library.


Is there any other option for this? Or, is my suggestion the best choice?



Answer



Your intuition is right - "prefer to study at X to to study at Y" is no good.


Your suggestion isn't bad, but it does sound a bit unnatural. "prefer ... rather than" is sort of strange considering that "rather" itself often means "prefer".




I'd rather study in a coffee shop than study in the library.



This usually expresses a preference for a specific event though rather than your general preferences. For alternatives so you can use the infinitive in the first clause and keep the expression general, use direct expressions of comparison (all of which work with both the infinitive and the gerund):



I prefer to study/studying at a coffee shop as opposed to studying in the library.


I prefer to study/studying at a coffee shop compared with/to studying in the library.


I prefer to study/studying at a coffee shop versus studying in the library. (uncommon in writing; fairly common in speech)



word usage - Comparative vs. Superlative While Comparing Two Items


In his book section 176, 3rd ed., Swan says:



Elder brother/sister are used when a person has only one brother/sister who is older; eldest is used when there are more. An elder son/daughter is the older of two; an eldest son/daughter is the oldest of two or more.




That was not clear enough; I don't see that here. Does that mean you can only use it if you have only one sister that is older than you (you don't have two or more sisters who are older than you ), or you can only use it when you talk about the youngest sister (out of two or more) that is older than you?



Answer



Big. Bigger. Biggest.


There can be only one "biggest" (and only one eldest sister|brother).


There can be several "bigger" (or several elder sisters|brothers).


I believe what Swan means to say is that one does not use eldest when there are only two siblings. If you have two apples, one of them is not the biggest of the two but the bigger of the two.


grammaticality - Question about "might like" vs. "would like"


Good evening! I took a modal verbs test at a website and one of my answers was marked off as wrong:



Julie might like to visit Kyoto when she is in Japan



I should've instead filled in "would", according to the provided answer sheet:



Julie would like to visit Kyoto when she is in Japan




What is wrong with the first sentence? One explanatory page says 'might' may be used to express future possibility. ("She might take the bus to get home.")



Answer



There is nothing wrong with the first sentence. It just expresses a different meaning than the second.


"Julie might like to visit Kyoto" indicates that Julie hasn't yet decided if she is going to plan the visit to Kyoto. She isn't sure if she wants to go. "Might" could also indicate that her decision to visit Kyoto depends on some other factor that we don't know about. "Julie might like to visit Kyoto, but if the weather is bad, she will stay in Tokyo."


"Julie would like to visit Kyoto" means that she definitely wants to go to Kyoto, but the trip has not been planned yet. There is still a chance that she won't go, but if you give Julie the choice, she will choose to visit Kyoto. It could also express that she wants to go to Kyoto, but cannot. "Julie would like to visit Kyoto, but train tickets are too expensive."


The phrases are very similar. They just express different degrees of how much Julie wants to go.


"Julie might like to go to Kyoto if the train tickets are not too expensive."
Julie has a little bit of interest in going to Kyoto, but it's not worth it to her if the train is expensive.


"Julie would like to go to Kyoto if the train tickets are not too expensive."
Kyoto is definitely on Julie's "places to visit" list, but she doesn't have a lot of money right now and might have to wait until a later trip to Japan to make it happen.



word request - What is the term for 'a......a.....a...' in speech?


Most Indians have this habit while speaking in English. It's not stammering that I'm aware of. It's not stuttering or bumbling either. I'm not sure what is it called.


The speech goes like this...



Hello everyone. I'm Maulik and here I am to present a..... our company's .....a....... balancesheet for the year of 2014-15. As we see, we are going through ...a.......lots of ups and downs in a......



How is 'a' pronounced there? It's the same way we pronounce this indefinite article with any noun. So, it's 'a' in 'a car'.


It's not just with Indians, I have seen many foreigners (even natives) with this habit but the frequency is quite less.


The video: (Check at 00:56 and 1:01) - Note: Irfan's English is still better! The people I'm talking about have loud and clear 'a......a....a'.


https://www.youtube.com/watch?v=7oyGj8pFChM



Listen it carefully. There are several such pauses. I'm not sure whether the narrator is native - http://www.bbc.com/news/world-asia-27577537



Answer



Most non-Indians have the same habit! It's called a dysfluency because for a moment your speech stops flowing (fluent literally means "flowing freely"). And Codeswitcher's answer is correct; these are often referred to as filler.


Of course, we don't usually write this sound down, but when we do we usually spell it uh, not a. Even though it sounds like the indefinite article, we don't spell it like that because it's not being used as an article. Some speakers of non-rhotic dialects spell the same sound er—since they don't pronounce /r/ in this position, er and uh describe the same sound.


You can find it in a few dictionaries under uh. They typically list it as an exclamation or an interjection, and from time to time you'll find people saying uh on purpose to indicate that they're at a loss for words (even if they aren't really):



Alice: How do you like my new hat?
Bob: It's, well, uh, er, um . . .



Bob is indicating that he can't think of anything nice to say. Poor Alice!



Friday, October 26, 2018

virtual reality - What's the proper codec and resolution to get 360° content projected on to spheres?


I'm using the Autopano Giga 4.4 and Autopano Video Pro 2.6 to stitch and create spherical content, but I've recently moved into wanting to create 360° tours via Unity. I know this is partly a developers question, but if anyone out there can help me with the right specs for exporting a spherical image or video from Giga to use to create the image for the inside of the sphere on Unity, I'd appreciate it!


Experimenting with Premiere and FCPX to edit highlight reels of spherical content, I've had seamless experiences created. For some reason in Unity, the images appear to be stretched around the sphere wrong and it's creates issues on the top and bottom of the image:


Example showing the artifacts at the base of the sphere


The image shown is the bottom of the sphere. I'm using the Android platform to hopefully turn these tours into apps when completed. Thank you for any help!




Learning To Create Better Art (2D Games)


Until one of my games "makes it" big, or I get flooded with gold ingots, I will have to handle most or all of my game art myself. The crux of my question is: how can I learn enough art to get beyond "programmer art" and into something I would actually be proud of?


The focus of my question is 2D, not 3D.



I already have a good grip on:



  • Photoshop/GIMP (image maniplation and creation)

  • Flash (animation and drawing simple art)

  • Simple drawing (by hand)

  • Digitizing hand-drawn art

  • Graphic design


However, games require complex and varied art; anything from backgrounds to icons, sprites, animation, and complex effects.


How do I bridge the gap, artistically? I already have the experience and confidence that I can do it; I only need to know the direction in which to put my modest efforts. I know this will pay off, especially in the long term. But I'm not sure how to get there.



Using existing art is something I already do, so please don't address that in your question.



Answer



Lots and lots of practice. Most artists have been doodling and drawing since they learned how to hold a pen, you need to make up for lost time.


My suggestion: start with hand drawn things and other basics. Having a grip on how a program works vs bringing out the fullest in a program for art are two different things so look up some online tutorials and the like and get a couple of new techniques.


Next: practice like crazy. My favorite way to do this is set up a list of things to make, usually simple things - get about 20 to 30 subjects (this is pretty difficult and you wont always use all of them). Then get an alarm clock you can set for 10 - 15 minute intervals set it and in that time do your best to draw up a single object.


When the alarm goes off thats the end of that drawing. No 'but's. You now have the option to begin the same object again (10 to 15 minutes again) or start the process all over again. (Rinse, wash, repeat until you get the desired effect)


grammaticality - "My hand breaks" or "My hand is broken"


Can you guys help me with my problem here. I"m confused between these two sentences:



My hand breaks




and



My hand is broken



As far as I'm concerned, for the first sentence "breaks" is a verb. Conversely, for the second sentence "broken" is an adjective. But is the first sentence grammatically correct? If it is, do both sentences indicate the same meaning?




word usage - Is it ok to say "The actor Tom Cruise's face shape is square"?


Ok, I often hear



I am Teacher Tom.




So I can deduce that I can say



I am actor Tom.



Then, my question is that:


Can I say



The actor Tom Cruise's face shape is square?




I feel it a bit awkward. But I don't want to say a long sentence like this



Tom Cruise is an actor whose face shape is square.




Answer



I would like to start with this:



I am Teacher Tom.



I don't know where you hear that often, but it doesn't sound like very good English to me. "Teacher Tom" sounds like a name used in a preschool. Better English would be:




I am Tom, a teacher.



or:



I am Tom, and I'm an actor.



If the sentence did not begin with "I am," you could use the word actor in front of Tom, like this:



I'd like to get the actor Tom in here for an interview.






As for talking about Tom Cruise and his face, I'm not sure you even need to add "the actor", because Tom Cruise is such a famous actor that most people already know what he does for a living. But let's say there's a carpenter in my town who happens to share the same name as the actor. Either of these sound okay to me:



Tom Cruise (the carpenter) has a square face.
The carpenter Tom Cruise is square-faced.



That said, if we are talking about the actor, we could say:



Tom Cruise is a square-faced actor.




That sentence is better than your original:



The actor Tom Cruise's face shape is square.



The reason your sentence sounds awkward is because it first identifies Tom Cruise as an actor (a fact that we already know), and then goes on to say that the shape of his face is roughly square. My version is slightly different; by using square-faced to modify the word actor (instead of the person Tom), we are differentiating Mr. Cruise from other famous actors with a remark about the shape of his face.


Thursday, October 25, 2018

questions - How do I understand Subject-Verb inversion?


I know Subject-Verb inversion is the format to form a question.


When we start a question with 'What',



What it means? -improper
What does it mean? -proper



But then, if we start the question with 'Who', where is the subject? Is 'Who' subject?




Who lives there? -looks much better than
Who does live there?



I would appreciate Native speakers' help in understanding Subject-Verb inversion.




movement - How can I incorporate the path of a jump into my A* implementation?


I need to calculate the path of a jump via A* for a simple platformer game. Calculating the direction is simple, but translating the jump physics into pre-calcuted voxel paths is a bit difficult. Especially when you factor things in like obstacles. Based on the image below, what is the best way to calculate jump in A*?


To give better context, here is a video of the game I'm working on. Will be implemented here to get companions following the player


http://www.youtube.com/watch?v=yMrbCtb2Buk


Jump Example



Answer




After heavily contemplating and consulting with many devs on how to solve this problem, I eventually came to the conclusion that A* on a pre-processed map is the best solution. Here's why:



  • Practically instant run time since A* traverses the map with everything it needs to calculate the jumps

  • Pre-processing can be performed at level load, fast enough to run again later after tile destruction

  • Clearance support is extremely achievable

  • Maps can be easily broken up into quadrants for extremely large tile amounts (1000 x 1000 voxels plus)


The process to use pre-processing with A* for gravity can be broken down into a few simple steps. If you already have A* this shouldn't take too long to implement.



  1. Calculate clearance values from collision tiles


  2. Discover all ledges by looking for missing tiles on the top, left, and/or right or a tile. Also get all walkable tiles

  3. Connect all ledges within the maximum jumping distance and that pass a simulated parabola line test (or physics but this will probably kill your runtime)

  4. Perform a runoff test on all ledges that draws a curved 135 degree angle in the direction of the ledge. Anywhere the test lands create another jump connection

  5. Run a drop test to see if fall locations are present on the sides of ledges

  6. A pre-existing A* implementation should be able to swallow this information with minimal tweaking since it can traverse through flat walkways and ledge connections now


Additionally here is an interactive demo I built based upon the above theory (source code available).


http://ashblue.github.io/pathfinding-platformer/


Wednesday, October 24, 2018

unity - How can I move number of objects between two points with random speed?


In the Hierarchy I have a Cube and the script is attached to the cube. And I also have in the Hierarchy two spheres as waypoints.


public class WP : MonoBehaviour
{
public Transform[] waypoints;
public float movingSpeed;

GameObject[] allLines;

GameObject[] duplicatedPrefabs;

private void Start()
{
allLines = GameObject.FindGameObjectsWithTag("FrameLine");

DuplicatePrefabEffects(allLines.Length);
duplicatedPrefabs = GameObject.FindGameObjectsWithTag("Duplicated Prefab");
}


private void DuplicatePrefabEffects(int duplicationNumber)
{
for (int i = 0; i < duplicationNumber; i++)
{
var go = Instantiate(prefabEffect);
go.tag = "Duplicated Prefab";
go.name = "Duplicated Prefab";
}
}


private void MoveDuplicated()
{
for (int i = 0; i < duplicatedPrefabs.Length; i++)
{
duplicatedPrefabs[i].transform.position = Vector3.Lerp(pointA.position, pointB.position, movingSpeed *Time.deltaTime);
}
}

void Update()
{

MoveDuplicated();
}
}

The duplicatedPrefabs are moving very very fast no matter what value I put for movingSpeed and then they are all stuck in the second waypoint and seems like moving on very specific small area on the second waypoint.


What I want to do is to move them smooth slowly between the two waypoints and with random speed range from each object. For example one will move at speed 1 the other on speed 20 third on speed 2.



Answer



It looks like you're trying to use Lerp as though it were MoveTowards. Lerp just picks a point between two extremes, it doesn't automatically move that picked point unless you change its inputs.


Try this instead:


for (int i = 0; i < duplicatedPrefabs.Length; i++)

{
duplicatedPrefabs[i].transform.position = Vector3.MoveTowards(
duplicatedPrefabs[i].transform.position,
pointB.position,
movementSpeeds[i] * Time.deltaTime
);
}

Two things to note here:





  1. This moves the prefabs toward pointB from wherever they happen to be. Make sure you're spawning them at pointA so they start from the right place.




  2. This assumes a parallel array of movement speeds for each object that you've populated in advance, using something like Random.Range()




complementation - Does 'reason' have a modifier and a complement?



Things couldn't have been worse.
Filch took them down to Professor McGonagall's study on the first floor, where they sat and waited without saying a word to each other. Hermione was trembling. Excuses, alibis, and wild cover-up stories chased each other around Harry's brain, each more feeble than the last. He couldn't see how they were going to get out of trouble this time. They were cornered. How could they have been so stupid as to forget the cloak? There was no reason on earth that Professor McGonagall would accept for their being out of bed and creeping around the school in the dead of night, let alone being up the tallest astronomy tower, which was out-of-bounds except for classes.
(Harry Potter and the Sorcerer's Stone)



Does the ‘reason’ license that-clause as its modifier and for-phrase as its complement?



Answer




The that is a relative clause and does not require licensing.


The for clause, however, is as you say a complement. Reason licenses clausal complements of several types:



  • a reason for going

  • a reason for them going

  • a reason for their going

  • a reason to go

  • a reason for them to go


adjectives - How to say that my English isn't very good?



A: My English is poor.
B: My English is not good.
C: I am not good at English.
D: My English is bad.



Which one is more appropriate to use in conversation?



Answer



Looking at these different sentences formed correctly about an idea, I don't think the OP's English is poor or bad. I would advise him not to be so humble. Nevertheless, he can use any of the sentences that he thinks is suitable.



c++ - How do components in a component based entity system


---Most of the stuff I am talking about I read here---



I am currently tring to wrap my head around component based systems to make a simple game engine of sorts.


I am having a hard time understanding how its supposed to work. I get that there are components which all inherit from the same base, which provides basic functions (init, update, end) and lets all of the different kind of components be stored in the same array of pointers. I get that. However I dont get how any efficient interactions of the components in a game object are supposed to happen.


Lets say I made a component that stores the amount of gold in a treasure chest (lets call it dataComponent). Lets also assume I made a component that does something when its update function is called (lets call it logicComponent)


There is also a class called Entity


class entity{
private:
vector components;
public:
void addComponent(component* comp);
void removeComponent(component* comp);

void getComponent(int id);
}

Lets now say I plan to make treasureChest, without any functions. Its just a background model. Then I will make a new enitity and using addComponent I will add the dataComponent(and give it 100 gold pieces in its constructor) and a logicComponent(and give it nothing in its constructor). The player might take out, or put in as much gold as he likes. We dont know how much gold there is in the chest. There might even be multiple dataComponents storing how many jewels or weapons are in the chest.


Example:


void main(){
Entity chest;
chest.addComponent(new dataComponent("gold",100)); //100 gold pieces
chest.addComponent(new dataComponent("guns",2)); //2 weapons
chest.addComponent(new logicComponent()); //this is going to do the printing

updateEnt(Entity);//simply iterates through all components of the entity and calls thier update functions.
}
EXPECTED OUTPUT:
This chest contains 100 gold and 2 guns

The logic components job is to somehow get its hands on the data and print it to the screen.


My question is: How can the logic component get access to the other components in the same object as it is in and access the approperate ones (the ones it needs to function) without looking through the entire array every single time?



Answer



Components are just a collection of data and logic. How you store and relate them to the logical entity is where you gain or lose performance depending on the strategy you choose.


My example and explanation is in Java, but the theory can be applied to any language.



The way I usually handle custom Component engines is with HashMap registries of components. This ends up with a game engine that looks a lot like a relational database. Lookups and data manipulation are fast, and it can easily handle millions of entities at a time in memory. It has been a while since I've built one, so I don't remember any cons to the approach, but maybe someone does and can improve this answer.


Essentially it boils down to HashMaps and GUIDs. Each Entity is nothing more than a Globally Unique Identifier (GUID) which serves as the key in each HashMap. A HashMap exists for every ComponentType in your game. There are ways to make this more general purpose, but I'm going with the naive solution for simplicity of argument.


We first need to track existing Entities. I do this with a HashMap with a GUID as the Key, and a boolean as the Value which indicates whether or not the entity should be destroyed.


public class Entity
{
HashMap entities =new HashMap();

public Entity()
{
}


public GUID create()
{
GUID entity= new GUID();
entities.put(entity,false);
return entity;
}

public HashMap getAll()
{

return entities;
}

public void markPurge(GUID entity)
{
entities.put(entity, true);
}

public void purgeReady()
{

//removes all entities that have a value of true,
//only called once all other purges have been called
for(GUID entity : entities)
{
if(entities.get(entity))
entities.remove(entity);
}
}
}


Lets say the object needs health, lets start with creating a Health component. During the initialization of your game, you'd create a HashMap to register Entities that have the HealthComponent.


public class Health
{
private HashMap healths=new HashMap();

public Health(){}

public void set(GUID entity, int health)
{
healths.put(entity, health);

}

public int get(GUID entity)
{
return healths.get(entity);
}

public void remove(GUID entity)
{
healths.remove(entity);

}

public void add(GUID entity)
{
healths.put(entity, 100);
}

public void add(GUID entity, int health)
{
healths.put(entity, health);

}

public void purge(ArrayList entities)
{
for(GUID entity : entities)
healths.remove(entity);
}
}

To spawn a new Entity with 100 health in our game, we first generate a new Entity GUID, then assign it a Health component.



public void setup()
{
//spawn an entity, and add a Health component in one step
Health.add(Entity.Create());
}

To actually use the components and assign game logic to them, I use Systems. Each System performs a piece of game logic, like destroying an entity if its health reaches zero.


public class DeathSystem
{
Entity entities;

Health healths;
public DeathSystem(Entity e, Health h)
{
entities=e;
healths=h;
}

public void update()
{
for(GUID entity : health.keySet())

{
if(healths.get(entity)==0)
entities.markPurge(entity);
}
}
}

Now we simply call our systems in our main game loop, after handling user input. Altogether yielding the following


Entity entities;
Health healthComps;

DeathSystem deathSystem;
GUID player;
boolean run = true;

public void main(String args)
{
setup();
while(run)
{
update();

}
}

public void setup()
{
entities= new Entity();
healthComps = new Health();
deathSystem = new DeathSystem(entities, healthComps);
player=entities.create();
healthComps.add(player);

}

public void update()
{
handleInput();
//attackSystem.update();
//healSystem.update();
deathSystem.update();
//finally, call the function that calls purge on all the component registries to remove any destroyed objects
purgeAll();

if(entities.getAll().size()==0)
run=false;
}

The beauty of this kind of structure is that all of your entity lookups are O(1) operations, and each System only operates on Entities currently registered as having the relevant components. Because of this, the systems only do what is absolutely necessary. If none of your entities have health, the death system has nothing to iterate over, and returns in constant time. This also keeps the memory footprint at an absolute minimum.


There are other approaches as well, but this is the one that I've had the most success with, and I think this illustrates that a component isn't so much an object, as a fuzzy collection of data and logic.


Tuesday, October 23, 2018

networking - Does it make sense to use both TCP and UDP at once?


After reading Is UDP still better than TCP for data-heavy realtime games?, I'm wondering if it makes sense to use both TCP and UDP at the same time, but for different things:




  • TCP for sending information that is sent infrequently, but should be guaranteed to arrive reliably.
    Such as score updates, a player's name, or even the on/off state of a light in the game world.





  • UDP for transmitting information that is updated constantly and can be lost occasionally, since newer information is always on the way.
    Such as position, rotation, etc.




Is this a reasonable idea? What are the possible drawbacks?
Are there better ways to handle this?



Answer



It results in packet loss for UDP due to contention between the two protocols - remember that UDP is not guaranteed delivery, while TCP is. More TCP packets will get through while UDP suffers - TCP induces UDP packet loss. There has also been the (historical) idea that router infrastructure favours TCP over UDP, though I doubt that is still true by this late stage.


I think you'd be better off finding one of the connection-oriented UDP protocols that is out there for use in games and the like, that offers you some of the benefits of TCP with none of its downsides. There are a few such, usually with a whitepaper detailing each concept.


An example of those is the open source Enet library, its primary feature being optional reliable, in-order delivery of packets over UDP.



phrase meaning - The expressions "This Monday" and "Next Monday"


Suppose it is Wednesday:




  1. Does the expression "This Monday" mean:




    • The Monday of the same week.

    • The Monday of the following week.




  2. Does the expression "Next Monday" mean:



    • The Monday of the following week.

    • The Monday of the week following the following week.





As an aside, I'm not even sure if the fact that this would work one way rather than another is a matter of which language is spoken (e.g. English), or whether the same reasoning as would be given by answers on this group would apply to other languages as well (as a matter of pure logic).



Answer



I agree with Tetsujin; native English speakers differ. I've heard native speakers use both meanings in each of the examples you give. I most often hear "this Monday" and "next Monday" to both mean "the Monday of the following week". And of course contextual cues can be used to determine if the speaker is intending "this Monday" to be in the past. "This Monday the weather was so nice I washed my car" is pretty clearly in the past.


I personally am in the habit of saying "this past Monday" and "this coming Monday" to clearly indicate which I mean.


c# - How to correctly draw a line in Unity



I'm working on a game which requires me to draw a few lines from a single point that is more formally said


Given point A with coordinates x,y I draw n lines where the i-th line has the coordinates named as xi,yi. Given the LineRenderer capabilities inside Unity3D I was unable to draw more than one line from a particular point with it since it renders only polylines.


I'm currently using the Debug.DrawLine() method which successfully renders the line. I have tried using GL.Begin() as it is shown in the Unity example but I cannot see my lines being drawn.


My question is : are there any other methods for doing this? If not, can you tell me how can I show the line that is being drawn with Debug.DrawLine() inside play mode? I've saw that I could use Gizmos.DrawLine() but I didn't quite understand it's usage.



Answer




I would recommend using the the GL API for drawing lines. The line thickness will always be 1px on screen and there is no option to change it. There will also be no shadows.


The GL method calls are executed immediately so you need to make sure to call them after the camera has already rendered.


Attaching the script to the camera and using Camera.OnPostRender() works good for rendering in the game window. To get them to show in the editor, you can use MonoBehaviour.OnDrawGizmos().


Here is the barebones code to draw a line with the GL API:



public Material lineMat = new Material("Shader \"Lines/Colored Blended\" {" + "SubShader { Pass { " + "    Blend SrcAlpha OneMinusSrcAlpha " + "    ZWrite Off Cull Off Fog { Mode Off } " + "    BindChannels {" + "      Bind \"vertex\", vertex Bind \"color\", color }" + "} } }");

void OnPostRender() {
GL.Begin(GL.LINES);
lineMat.SetPass(0);
GL.Color(new Color(0f, 0f, 0f, 1f));
GL.Vertex3(0f, 0f, 0f);
GL.Vertex3(1f, 1f, 1f);
GL.End();
}


Here is a full script that attaches all of the given points to the main point. There are some instructions in the comments of the code to get it set up right and about what is going on.


If you are having problems changing the color of the connecting lines, make sure to use a shader on your line material that takes into account the vertex color such as Unlit/Color.


using UnityEngine;
using System.Collections;

// Put this script on a Camera
public class DrawLines : MonoBehaviour {

// Fill/drag these in from the editor


// Choose the Unlit/Color shader in the Material Settings
// You can change that color, to change the color of the connecting lines
public Material lineMat;

public GameObject mainPoint;
public GameObject[] points;

// Connect all of the `points` to the `mainPoint`
void DrawConnectingLines() {

if(mainPoint && points.Length > 0) {
// Loop through each point to connect to the mainPoint
foreach(GameObject point in points) {
Vector3 mainPointPos = mainPoint.transform.position;
Vector3 pointPos = point.transform.position;

GL.Begin(GL.LINES);
lineMat.SetPass(0);
GL.Color(new Color(lineMat.color.r, lineMat.color.g, lineMat.color.b, lineMat.color.a));
GL.Vertex3(mainPointPos.x, mainPointPos.y, mainPointPos.z);

GL.Vertex3(pointPos.x, pointPos.y, pointPos.z);
GL.End();
}
}
}

// To show the lines in the game window whne it is running
void OnPostRender() {
DrawConnectingLines();
}


// To show the lines in the editor
void OnDrawGizmos() {
DrawConnectingLines();
}
}


Further note on shadows: I explored using a geometry shader to make shadows but since the GL calls run immediately, they are not in the normal rendering pipeline and AutoLight.cginc and Lighting.cginc won't pick up the ShadowCaster pass.






If you need to change the line thickness and want to have realistic shadows. Just use a cylinder mesh and scale the height.


Here is a script that will make a cylinder to connect each point to the main point. Place it on a empty game object and fill in the parameters. It will hold all of the extra connecting objects.


using UnityEngine;
using System.Collections;

public class ConnectPointsWithCylinderMesh : MonoBehaviour {

// Material used for the connecting lines
public Material lineMat;


public float radius = 0.05f;

// Connect all of the `points` to the `mainPoint`
public GameObject mainPoint;
public GameObject[] points;

// Fill in this with the default Unity Cylinder mesh
// We will account for the cylinder pivot/origin being in the middle.
public Mesh cylinderMesh;



GameObject[] ringGameObjects;

// Use this for initialization
void Start () {
this.ringGameObjects = new GameObject[points.Length];
//this.connectingRings = new ProceduralRing[points.Length];
for(int i = 0; i < points.Length; i++) {
// Make a gameobject that we will put the ring on

// And then put it as a child on the gameobject that has this Command and Control script
this.ringGameObjects[i] = new GameObject();
this.ringGameObjects[i].name = "Connecting ring #" + i;
this.ringGameObjects[i].transform.parent = this.gameObject.transform;

// We make a offset gameobject to counteract the default cylindermesh pivot/origin being in the middle
GameObject ringOffsetCylinderMeshObject = new GameObject();
ringOffsetCylinderMeshObject.transform.parent = this.ringGameObjects[i].transform;

// Offset the cylinder so that the pivot/origin is at the bottom in relation to the outer ring gameobject.

ringOffsetCylinderMeshObject.transform.localPosition = new Vector3(0f, 1f, 0f);
// Set the radius
ringOffsetCylinderMeshObject.transform.localScale = new Vector3(radius, 1f, radius);

// Create the the Mesh and renderer to show the connecting ring
MeshFilter ringMesh = ringOffsetCylinderMeshObject.AddComponent();
ringMesh.mesh = this.cylinderMesh;

MeshRenderer ringRenderer = ringOffsetCylinderMeshObject.AddComponent();
ringRenderer.material = lineMat;


}
}

// Update is called once per frame
void Update () {
for(int i = 0; i < points.Length; i++) {
// Move the ring to the point
this.ringGameObjects[i].transform.position = this.points[i].transform.position;


// Match the scale to the distance
float cylinderDistance = 0.5f*Vector3.Distance(this.points[i].transform.position, this.mainPoint.transform.position);
this.ringGameObjects[i].transform.localScale = new Vector3(this.ringGameObjects[i].transform.localScale.x, cylinderDistance, this.ringGameObjects[i].transform.localScale.z);

// Make the cylinder look at the main point.
// Since the cylinder is pointing up(y) and the forward is z, we need to offset by 90 degrees.
this.ringGameObjects[i].transform.LookAt(this.mainPoint.transform, Vector3.up);
this.ringGameObjects[i].transform.rotation *= Quaternion.Euler(90, 0, 0);
}
}

}


word usage - Can I omit the verb "eat" and noun "food" in this sentence?



I didn't know what food you'd like (eat), so I prepared many (food).




Is the sentence still grammatical if I omit eat and food? Why or why not?



Answer



Yes, you can omit both words, although it should be to eat (not eat), and many foods (not many food).


It's OK to omit to eat, because you can omit the infinitive verb if it's fairly obvious what that verb would be. In this case, you can safely assume that food is something you eat. Technically, you can do other things with food, such as put it in a freezer or throw it away. But from the context of the sentence, it's pretty clear that this prepared food is meant to be eaten.


You can also omit foods, because, similarly, you can omit a noun if the reader can reasonably guess what the noun should be from the adjective describing it. It is obvious from the context of the sentence that foods (or dishes) are being prepared. Really, the only noun in the sentence, aside from I and you, is food, so many has to describe foods.


definite article - " the people "?



"You know, every time we take rebels, whether it’s in Iraq or anywhere else, we’re arming people. And you know what happens? They end up being worse than the people.”



https://www.washingtonpost.com/news/the-fix/wp/2016/10/09/everything-that-was-said-at-the-second-donald-trump-vs-hillary-clinton-debate-highlighted/



What does the definite article imply here exactly? Why is it "the people" and not just "people"?




Monday, October 22, 2018

grammar - Verb agreement: We [company name]


I have seen a company description as follows:
We [company name] is a specialized manufacturer of…
Is the verb agreement correct here?



Answer



It's an appallingly ungrammatical construction, caused by someone trying to slavishly follow the principle that in American English, collective nouns almost always trigger singular verb agreement. That issue doesn't arise in "British English", since we quite naturally use singular or plural for things like company, family, group, according to context.



But I don't think any competent speaker (not even an American) would actually produce OP's example. So presumably the company (or at least, the speaker) is not a native speaker of English.


difference - Does the position of "only" give a different meaning to the sentence?





I've only been there once. (OALD)



Does this mean ‘I’ve just been there not doing particular activities like studying or staying for particular something else, and I have once? (Because ‘only’ is put between verbs, it is different from ‘I’ve been there only once’.)



He has only seen her once. (The Cambridge Grammar of the English Language)



Likewise, does this mean ‘he has just seen her not talking to each other et cetera, and he has once’?



Answer



Actually it's not at all different from "I've been there only once." The two sentences have the exact same meaning. "I've only been there once" is certainly more idiomatic, and you might be able to argue that it emphasizes the only a bit more since it appears nearer the beginning of the sentence. But there is no difference in meaning.



To elaborate on the possible small distinction in emphasis that could be made:



I've been there only once.



The statement is that you have indeed been there; but you're adding that you've only been there one time.



I've only been there once.



You're leading with the only, emphasizing that your being there has only happened one time.


But this is a very slight distinction, and the meaning (that you've been there one single time) is exactly the same no matter which way you phrase it. I think "I've only been there once" is more idiomatic, but beyond that it's your choice which you use.



Sunday, October 21, 2018

negation - Any differences between "I didn't have many apples" and "I had few apples"?


We all know that "I had a few apples" and "I had few apples" are different.


I wondered what the possible differences would be in the meaning of these two sentences:




I didn't have many apples.
I had few apples.



Well, we know that "few" is a negative quantifier and it's the opposite of 'many'. But do the two sentences convey precisely the same meaning?



Answer



Yes, they convey different meanings.


Down-to-Earth




  1. I didn't have many apples.


  2. I had few apples.



Simply put, sentence one conveys the meaning that the speaker didn't have as many apples as it would take to call the apples "many". Sentence two tells us that the speaker had a small number of apples.


They could mean the same, but they do not. "I didn't have many" means "I had less than what could be called many". That has a broad meaning: I could be having a relatively large amount of apples, but not as many that would fit the label "many". However, "I had few" means "I only had a small number". It couldn't imply the meaning "I didn't have many" represents. In other words, sentence two implies sentence 1, but sentence 1 has a more general meaning. Take a look at the diagram I draw to get a better picture. A more elaborate description is given below.





Technically . . . 


More info on this can be found on Cambridge Grammar of English Language §5.2 — scalar entailments and implicatures; page 366–368.


CGEL points out that negating "many" results in a paucal implicature. It's useful to compare this pair to the more restrictive negative quantifier "no". Indeed, "few" is the opposite of many; but "not many" is not as restrictive as them. Compare these four instances:





  1. None of the sailors tried to defend their captain.

  2. Few of the sailors tried to defend their captain.

  3. Not many of the sailors tried to defend their captain.

  4. Not all of the sailors tried to defend their captain.



We can apply what's been said here. "None" is the most restrictive,; "few" is less restrictive than "none" but still more than the other pairs, "not many" is only more restrictive than "not all".


Hence, we can say that if sentence one is true, so are others. If sentence two is true, then so are 3 and 4, but we can't judge whether one is correct or not; and the same story goes for three and four. If we know that not all of the sailors helped their captain, we can't necessarily judge whether none of them helped the captain, or there were only a few exceptional sailors that didn't help the captain.





However, it should be noted that this difference in meaning is very subtle and may go unnoticed, since this was all about implicatures: context-dependent. We can conclude that the sentences do not convey 'precisely' the same meaning, although the difference is passable in most cases.


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