Friday, August 31, 2018

opengl - Do I lose/gain performance for discarding pixels even if I don't use depth testing?


When I first searched for discard instruction, I've found experts saying using discard will result in performance drain. They said discarding pixels will break GPU's ability to use zBuffer properly because GPU have to first run Fragment shader for both objects to check if the one nearer to camera is discarded or not. For a 2D game I'm currently working on, I've disabled both depth-test and depth-write. I'm drawing all objects sorted by their depth and that's all, no need for GPU to do fancy things. now I'm wondering is it still bad if I discard pixels in my fragment shader?



Answer



Graphics hardware can perform early depth-based culling of fragments before computing their color value (in other words, before running your fragment shader). Consequently, if you utilize any features that would affect that, such as discard, alpha-testing, or manipulating gl_FragDepth the hardware's ability to do that optimization will be compromised since the true depth of the fragment cannot be assumed and the full shader must be run.


Whether or not the use of any of those compromising features has a net observable performance impact depends on the situation, though. The early-z optimization can improve performance if you have very expensive fragment shaders, for example, but if the cost of your pipeline is in the vertex shader (or elsewhere) it won't benefit you as much, and consequently you may see little or no performance degradation by using discard.


Disabling the depth test entirely via the API should prevent the optimization from running as well, since it could result in incorrectly-rendered scenes. In your case, then, it shouldn't matter that you use discard.


Recent hardware can force the tests (including early stencil tests) using layout(early_fragment_tests) -- there is more information (and caveats) on this on the page I linked in the beginning of the answer.


xna 4.0 - Error on new XNA 4.0 game project - No suitable graphics card found


Any ideas on how to fix this? According to what I remember about XNA 3 was that when running the application from scratch, I would get a blue colored windows with nothing rendered.


Any suggestions?


alt text


EDIT!


I right clicked the project and selected Properties and changed the Game Profile from Use HiDef to Use Reach. Now the familiar blue tint window is showing as expected. alt text


What am I losing if I choose the limited API and why did I even have to choose this for it to work?



Answer



To answer your follow up question:




What am I losing if I choose the limited API?



This blog post explains the differences between Reach and HiDef. In a nutshell, the Reach profile does not allow the use of some of the more advanced graphics card features. But it runs on more hardware.


meaning in context - Where we are exactly if we're "at the sea"?


I'm familiar with some serious discussions about preposition particularly when it comes to kind of "at" vs "in" involved. I know that "at" suggests a point in space and "in" requires being confined, enclosed in the area. Taking all the information we know into consideration, where does one imply to be exactly by saying "I'm at sea" (apart from its idiomatic meaning for sure).


Is he far away from the coast on the water in/on the boat or any vessel? Or is he on the coast anywhere near the sea? Or both are possible?


After learning the fact that "being at sea" and "being at the sea" are not the same thing, I have to include the following question in my post ; - how come the article "the" make such a difference like "being close to the sea(seaside)" and "being on an open sea/ocean" ? (please mention it in your answers)




Thursday, August 30, 2018

articles - "the most X" or "most of the X" in this sentence


I wrote:



In the worst case, when the most patterns are defined using either “Parent” or “Common Ancestor” options, a sub-tree of the DOM-tree must be revisited after visiting some nodes, which are assumed to be all the nodes in the worst case.



I am talking about specific patterns and nodes. So, I thought maybe it should be:



In the worst case, when most of the patterns are defined using either “Parent” or “Common Ancestor” options, a sub-tree of the DOM-tree must be revisited after visiting some of the nodes, which are assumed to be all of the nodes in the worst case.



Are these two sentences equal? I think the second sentence is what I want because I am talking about specific nodes and patterns, but are there shorter ways to say the bold phrases without ".. of the .."?



Can "the most patterns" be equal to "most of the patterns"? I think no, since the "the" in the former indicates the top group of something general...


Besides, How can I avoid repeating "in the worst case" in the sentence above?


Can I shorten the last part to:



In the worst case, when most of the patterns are defined using either “Parent” or “Common Ancestor” options, a sub-tree of the DOM-tree must be revisited after visiting every node in the worst case.



I want to say the some nodes in the worst case are assumed to be all the nodes.




verbs - "Trade in" meaning



This is coming from TOEFL listening.


Given that a student bought a wrong book for her class, and then she said,



the bookstore let me trade in my old version for the correct version without any trouble.



Does this verb "trade in" here mean same with "swap"?



Answer



the term "trade in' usually does not mean exactly the same as 'swap', although the concepts are similar.



A swap is a direct exchange. There is usually not any additional payment made by either party. e.g. I will swap you my watch for your bicycle. Generally 'swaps' are an informal method of trade between friends or non-business people.


A trade in is a method of buying in which you surrender an item you currently own as part payment on another item that you wish to buy. The term is most frequently used in the automotive sales industry where a buyer trades in an older model vehicle as part payment for a newer model. Generally 'trade ins' are a formal method of trading offered by a business to a consumer.


In the example that you mentioned, it is likely that the bookstore allowed the student to trade in the wrong book at its original purchase value. (assuming it was still in original condition.) This money would then be used to offset the cost of the right book. If the right book was more expensive then the student would have to pay the difference in price. Similarly, if the right book was less expensive then the student would have been given a refund.


word meaning - "said" as an adjective




In our electron pump, when you turn the crank, one side gets a surplus of electrons, or a negative charge, and on the other side the atoms are missing said electrons, resulting in a positive charge.



The part in a bold font is confusing to me. I can't make grammatical sense of it. One side gets a surplus of electrons and the other side gets the atoms. How does are missing said electrons fit into the rest of the sentence?



Answer




In our electron pump, when you turn the crank, one side gets a surplus of electrons, or a negative charge, and on the other side the atoms are missing said electrons, resulting in a positive charge.



Said here means which are mentioned earlier in the text, or, simply, these. The sentence could be rephrased thus:



In our electron pump, when you turn the crank, one side gets a surplus of electrons, or a negative charge, and on the other side the atoms are missing these electrons, resulting in a positive charge.




So, as an atom misses an electron (the electron's orbital is empty), it assumes positive charge.


absolute clauses - Is 'The customer having left, ...' a dangling participle?



I found the following sentence in one of our questions: Use of "having" in English,



The customer having left, the criminal takes out a pin from his purse and scrapes off hardened glue from the edges of the keys.



It gave me a grammar warning immediately. After thinking about it for a while, I concluded two points:




  • The phrase The customer having left looks odd as a participle phrase. It should be just Having left. But then again, if the part The customer were removed, we would have gotten another kind of error, and the meaning would have been changed.





  • It seem like The customer having left is a dangling participle phrase. The phrase itself and the main clause don't seem to cohere well enough. Some conjunction such as after should have been added, or the sentence should have been revised.




So I would like to ask: Is the phrase 'the customer having left' above good English?


NOTE: I personally don't think it is, otherwise I could write something funny such as this:



John walking into the woods, I followed him, we walking together for two hours, John walked, I walked, John having fallen down, I picked him up, we continuing walking, I like the woods, the woods smelling nice, John saying something, I didn't hear him, we continuing walking, John keeping walking, this was so much fun.




Answer



It is not a dangling participle per se, but rather an example of an absolute (which I was taught to call nominative absolute).



A so-called "dangling participle" is a participial phrase which is ambiguous as to what it modifies, e.g.



Watching the sunset, the beach went silent.



In the above case, the sentence reads as if the beach were watching, rather than the people.


In the construction you have cited, there is no ambiguity as to who is leaving; it is clearly the customer. The construction serves to provide contextual information, essentially modifying the entire sentence or clause. It does not modify any individual word in a sentence, and can be removed without changing the meaning, hence the term absolute (borrowed from Latin grammar and its ablative absolutes).


I would not say absolutes are especially common, but they are a familiar feature:



Economically speaking, Turkey has performed well.


The committee having completed its business, the meeting was adjourned at 12:00 noon.



A well regulated Militia, being necessary to the security of a free State, the right of the people to keep and bear Arms, shall not be infringed.



c# - Fast, simple procedural 2d island generation



I need to generate tile data for an island based rpg, my goal is have something that looks like this (mountains not required):


enter image description here


For the past few days I have been trying to figure out a satisfactory way to generate tile data that will give me varied and natural islands, such as in the example above.


I've tried using Unity's Mathf.PerlinNoise but the results are far too random, and I can't see a way to get it to generate a single island.


Using LibNoise I was able to get slightly better results, although the generation seems to be significantly slower and perhaps better suited to 3d terrain. Similarly however, I can't see a way to set the Octaves/Frequency/etc, so that I get a nice single island each time.


While there are a fair amount of resources online for perlin/noise in general, it mostly seems to be aimed at 3d terrain and height, where I simply have a 2d array of int for my tile data, that maps to either water, sand or grass and needs to be generated in such a way that sand/grass are grouped together logically to form an island.


Any help would be greatly appreciated!



Answer



One thing I've done in the past for island shapes is to use perlin noise minus a circular shape. It usually produces one big island and some little things off on the side. You can use flood fill or smoothing to remove any small noise.


Here's a demo (flash) that I wrote for this question.



For each location (x, y) in the noise bitmap, compute the distance from the center, normalized so that the bitmap is 2x2:


function distance_squared(x, y):
dx = 2 * x / width - 1
dy = 2 * y / height - 1
# at this point 0 <= dx <= 1 and 0 <= dy <= 1
return dx*dx + dy*dy

Location (x, y) is part of the island if perlin_noise(x, y) > 0.3 + 0.4 * distance_squared(x,y). In the demo you can vary the two constants to see the effects you can get.


I don't think these islands look quite the way you want but this technique might be useful for you in combination with other techniques you're using.


Wednesday, August 29, 2018

sentence usage - When to properly use Present Progressive statements?


Can present progressive statements be use at present or for the future? or both?




prepositions - I look forward to hearing from you or looking forward to hear from you?


Should I say



I look forward to hearing from you



or




looking forward to hear from you?



I have doubt because I know that the form of a verb is "to+ infinity" without the addition of the -ing that changes it to become a noun.



Answer



This is a very common mistake!
So, don't worry. Here is the cure.


Ask yourself which one makes more sense: "look forward to it" or "look forward to do it"?


Chances are you know that "look forward to it" sounds more natural, because you've seen or you've heard others use it that way before. And, yes, with look forward to, you need hearing from you (NOT hear from you).





Grammar points


The trick is to remember that to can be either the infinitive marker or a preposition1.


You need a verb after the infinitive marker to (e.g. I want to swim this evening).
You need a noun after a preposition (e.g. She went back to the pool.)



It doesn't have to be a real noun, just something that functions like a noun. In other words, it's the object of a preposition, as it's traditionally called; or as defined a little more precisely (same link):



The prepositional complement is typically a noun phrase, but it may also be a nominal relative clause or an -ing clause. Both the nominal relative clause and the -ing clause have a range of functions similar to that of a noun phrase: ...
(emphasis mine)





In your example, to in look forward to is a preposition. Why? Because you can say look forward to something (e.g. He had worked hard and was looking forward to his retirement.) In other words, saying "I'm looking forward to it" makes sense.


And that makes you need a noun or something noun-like, i.e., hearing, not hear:
I look/'m looking forward to hearing from you.


1When the preposition to is used in a phrasal verb, some people call it a particle, but let's keep this post simple and use only the term "infinitive marker" and "preposition".) Here is a list of such phrasal verbs (ending with to). Some common ones, in my opinion, are look forward to and be used to. Another common phrasal verb (but not on that page) is object to.




Bonus


Here is a related mistake which shares the same cause of confusion: used to vs. be used to.


Remembering this may be helpful:




He used to live in Frankfurt, but he's not used to living in cold weather.



The first to is the infinitive marker to. The second to is a preposition.
The first to is about "He used to do something".
The second to is about "He's not used to something".


pronunciation - How are silent letters important?


Some words use silent letters in the spelling. I often ask myself: why are they used? English is a global language and it is changing day-by-day.
Even if I have to believe they exist as they were in the words originally, why should we still retain them?


Various spellings have been changed for this pronunciation change, like "colour" to "color", "centre" to "center", "catalogue" to "catalog", then why are we still using "H" for "honest" or "P" for "Psychology"?


Do these letters help native speakers to picture the spelling in their minds somehow? And if not, why are they still being used?



Answer



There are several reasons, three of which stand out:





  1. If you keep the original spelling, connections with the same word used in other languages remain intact. In honest and psychology, for example, this makes it easier for people to communicate across English, French, Latin, Greek, etc. In German, they spell Zentrum. This makes it harder for us to remember how it is spelled, and sometimes this even makes it harder to learn the word for learners. Similarly, Dutch spells akkoord, which is again less consistent with many other languages and the language of origin, French.




  2. It is terribly hard to get people to change the way they have always spelled words. Imagine if you had to change your spelling all of a sudden after having spelled a certain word the same way for 30 years! Or, what may be even worse, regular spelling changes occurring every 5 years, which nobody will be able to learn or keep up with, as in Dutch. And, even if you decide that something needs to change, there will be 1001 opinions as to how. Should it be onest? onnest? onnist? As it is, no spelling system in the world is wholly phonetic, not even new systems. Imagine you had to read a teks laik this, weh ai'uhv tsyowsin suhtin konvensyuhns.




  3. How will you take into the account the fact that people in different regions pronounce the same word differently? Should all spelling be based on the phonetics of Received Pronunciation? Or should each region use its own spelling, making, say, British harder to read for Australians and vice versa?





legal - Issues using real names in a soccer player game



Is illegal to use the real player and team names in a game? When I say game could be and desktop, mobile or fantasy game.


If is illegal, is ok to change a little bit names? Instead of using Messi could I use Messsi (or something similar)?


All gambling and statistics soccer websites have permissions to use those names?



Thanks!



Answer



No, not generally. Not without permission.


Gambling and stats sites are a different case. There's a difference between using someone's name in a factual article about that person and using their name and likeness in a FIFA-like game.


Minor spelling variations are not enough, otherwise we'd all be playing Lorrd of teh Ringz games.


prepositional phrases - Too many "the"s here. Should I delete some?


I have a sentence:



The Theorem states the properties of the solution of the model.



Too many "the" here... Is there anything wrong in grammar?



Answer



You're relying too heavily on the phrase "of the" to attribute nouns to other nouns in terms of ownership.



You can add verbs to this sentence to help remove the "thes" if you don't like the sentence now. However, nothing is technically wrong with it. The verbs will perform the attributing for you, instead of "of."



The Theorem states properties exhibited by the model's solution.



I don't know if "exhibited" is the right verb here. You'll have to analyze your own context to use the correct word.


You can also attribute these nouns to their owners or creators via possession to further eliminate usage of "the." For example:



Einstein's Theorem states properties exhibited by his model's solution.



Or:




Einstein's Theorem states the properties of his solution of the model.



Again, you'll have to analyze your own context to figure out what nouns need to be attributed to whom.


tense - When should I use "didn't" instead of "haven't"?


Is haven't supposed to mean something I may still do and didn't not?


Can I use didn't for something I might still do?




Answer



Haven't and didn't are different time-wise, as you have guessed correctly. Haven't refers to the past up until now. So if you haven't done something, you haven't done it for a specific period of time (day, month, ever, etc.)


Didn't refers to a specific point of time that has already passed. For example, if it is 7 PM, you could say "I didn't eat dinner at 6" or "I haven't eaten dinner yet today". In both instances, you can still eat dinner. Plus, it is possible for you to have eaten dinner at a different time if you use didn't, but not with haven't, since you specified today.


Tuesday, August 28, 2018

How can I capture every frame in DirectX 9 using a shader


This is actually a follow up to this question How to capture the screen in DirectX 9 to a raw bitmap in memory without using D3DXSaveSurfaceToFile


The proponent of the best solution suggested that I should look at a shader program to capture the screen. How could I do that. I have no clue on how can I use a shader program to do that.



Answer



Shaders don't capture the screen in and of themselves. What's being suggested in the "shader based approach" is to:



1) Use render-to-texture or the like to render your entire scene to a single texture 2) Render that texture (with, say, a fullscreen quad) to your final output (or another texture if you want to chain effects or do multi-pass effects) using pixel and/or vertex shaders written in HLSL to apply your filtering effect instead of C++.


This has the advantage of keeping everything in GPU memory instead of spending your limited memory bandwidth copying everything from GPU to system memory (where C++ can work on it) and back (where it can be rendered.)


Methods of note for wrangling pixel shaders (commonly used for operations such as bluring, depth of field effects, tinting, you name it): D3DXCompileShaderFromFile, CreatePixelShader, SetPixelShader, SetPixelShaderConstantF


And for render targets: SetRenderTarget, BeginScene, and EndScene.


Sequence of tenses for facts irrelevant of the moment of speech


Let's consider two sentences:



(1) I suggested that the word zeitgeist was of German origin.
(2) The lecturer said the Pluto's orbital period is more than 200 years.




In both cases, the facts are always valid and irrelevant of the moment of speech and context. I've heard sequence of tenses is not required in such cases. Are past and present tenses interchangeable in both of them? Would it be correct to say:



(1) I suggested that the word zeitgeist is of German origin.
(2) The lecturer said the Pluto's orbital period was more than 200 years.





Scene Graph Theory


I have a scenegraph that represents the whole world. However, at the moment if there are multiple copies of the same scene graph (aka the same model) it will just create a new scenegraph linking. This works, however, the loading time is insane. Which is to be expected. I have tried to load the model's scene graphs and simply just have the world link to these. However, when I need to travel up the scenegraph the model doesn't know anything about the world unless you count the last one that was using it. Making it impossible to render the models in the right place as everytime you travel up the scenegraph you get into the problem of not knowing where to go from the models node to get to the world node.


For example I have a scene graph for each model in the world, like a boat has a scene graph. If I want multiple copies of the boat in the world at the moment I will have to load the boat x amount of times. Which I don't want. I want to be able to specify the boat, load it, then have a world scenegraph which specifies down at the leaf nodes (Load boat). What is a design that would solve this problem?



Answer



You seem to be treating your scene graph as a tree - each scene contains N boats, each of which contains its own copy of the "boat" scene graph, etc. This is not fundamentally wrong, but can certainly be improved upon. The following diagram illustrates my understanding of your current approach, for a scene with two boats1:


Scene tree


Rather than storing N copies of the "boat" scene graph if you have N boats, instead create N copies of a "SceneGraphReference" node that all reference a single copy of the "boat" scene graph. Each such node should maintain its own position/rotation/scaling etc information, so that the bulk of the information (the "boat" scene graph) is only stored once, but the information necessary to draw multiple copies in different places (position etc) is stored as often as necessary. This would look something like the following, for the same example with two boats:



Scene graph


To put this in more technical terms, your current approach is an N-ary tree: consider using a unidirectional acyclic graph instead2.





  1. Please excuse my (minor) abuse of UML diagrams.

  2. Interesting things can be achieved by relaxing the unidirectional and acyclic restraints (i.e. using a plain old unrestricted graph), but that's a discussion for another time.


3d meshes - How to export 3D models that consist of several parts (eg. turret on a tank)?


What are the standard alternatives for the mechanics of attaching turrets and such to 3D models for use in-game? I don't mean the logic, but rather the graphics aspects.


My naive approach is to extend the MD2-like format that I'm using (blender-exported using a script) to include a new set of properties for a mesh that:





  • is anchored in another 'parent' mesh. The anchor is a point and normal in the parent mesh and a point and normal in the child mesh; these will always be colinear, giving the child rotation but not translation relative to the parent point.




  • has a normal that is aligned with a 'target'. Classically this target is the enemy that is being engaged, but it might be some other vector e.g. 'the wind' (for sails and flags (and smoke, which is a particle system but the same principle applies)) or 'upwards' (e.g. so bodies of riders bend properly when riding a horse up an incline etc).




  • that the anchor and target alignments have maximum and minimum and a speed coeff.





  • there is game logic for multiple turrets and on a model and deciding which engages which enemy. 'primary' and 'secondary' or 'target0' ... 'targetN' or some such annotation will be there.




So to illustrate, a classic tank would be made from three meshes; a main body mesh, a turret mesh that is anchored to the top of the main body so it can spin only horizontally and a barrel mesh that is anchored to the front of the turret and can only move vertically within some bounds.


And there might be a forth flag mesh on top of the turret that is aligned with 'wind' where wind is a function the engine solves that merges environment's wind angle with angle the vehicle is travelling in an velocity, or something fancy.


This gives each mesh one degree of freedom relative to its parent. Things with multiple degrees of freedom can be modelled by zero-vertex connecting meshes perhaps? This is where I think the approach I outlined begins to feel inelegant, yet perhaps its still a workable system? This is why I want to know how it is done in professional games ;)


Are there better approaches? Are there formats that already include this information? Is this routine?



Answer



Yap. Bones formats. MD2 is a vertex animation format, not bones based format. And in Blender, depends on the version you're working with, but can probably make use of:




  • Directx *.x (I think in both 2.49 and 2.56 beta)

  • *.md5 . Doom III, like md2, from Id Software, but much better than md2. Md2 has vertex position accuracy problems, normals/lighting problems, UVs have its issues too, etc. Still, all blenders do export it, and can be useful for the flag animation. But you can asign some bones to the flag, some weight painting, and have same effect.Even easier.

  • Collada. But it is still not ended, in certain newest builds at graphicall.org I have checked to be working, at least in basic stuff which you need.

  • You need to use Blender 'constraints' in your bone animations, to have the behaviours you mention, and then export with those "baked". Then code would do the rest.(and don't quote me on this, but I think md5 did export constraints also. And that you can use a md5 version with blender 2.41. I think , set as an addon, md5 can work well with 2.56, but have not tried yet.)


A good knowledge of Blender rigging (bones, weights, constraints) system and formats is quite needed for this, but seems pretty doable.


A lot of people just used to use Milkshape, ideal for these kind of things, and there were very good loaders for game programmers, for ms3d format.


IMHO you can achieve the same by loading for example an md5, there are good loaders out there, and am told is an easy to handle format for programmers. Collada anyway might be the best in long run: Is the definite Blender's bet, and in general, everybody, engines, etc, are trusting on it. But it's a very complex format, so making a loader might be hard, unless you can grab sth already made or whatever. I don't know, that's the programmer side of things.


Monday, August 27, 2018

"The" before a superlative adjective: why there is no definite article in "Your woodwork was worst of all"



I'd like to know, if you could tell me this :D
So, there's this sentence:



Your woodwork was worst of all.



And there's the other one:



The 4th of July was (the?) hottest day this summer.



I wonder why there is no "the" in the first one? And why in the second one there is?



English is not my native language, so can someone explain it to me in the most simple way? :D Thank you




word usage - "This product is good value" vs "This product is of good value" in a sentence


1.This product is good value.
2.This product is of good value.


Are there any difference in meaning between "good value" and "of good value"?




2d - How to Create Snakelike Objects


I am working on a 2D action platformer in Python, though my question is a general one about creating snakelike objects which move in a variety of patterns.


I have noticed this kind of object in many 2D games. For example, this boss in Contra has snakelike arms.



enter image description here


And this enemy from Super Metroid clearly seems to be composed of multiple segments.


enter image description here


I want to create snakelike objects in my game, though I don't know where to begin or what I may need to add to my physics engine to support them.


So far, all my enemies and hazards consist of single sprites and are programmed using simple attributes like velocity, acceleration, parametric curves, etc.


Maybe I need to create a class for the segments, designate one segment instance as the leader, and update the positions of the other segments based on the position of the segment in front of it. But how do I program different patterns of movement? Do I need to learn about so-called joints and implement them between the segments? I currently don't have them in my engine.


I know I could easily create a segmented object where each non-leader segment is moved to the previous position of the segment in front of it (like in classic Snake, described here), but I want more complex patterns than this. Sometimes I may want the object to be flailing from an anchored point, and other times I may want it to be following some pattern across the screen.


I really don't know where to begin in trying to create this kind of object and would greatly appreciate any advice.


How do you implement snakelike objects with a variety of movement patterns?


(Given the ubiquity of this kind of object in games, I was surprised that I couldn't easily find much about it online. I think a detailed write-up on it would be cool.)




Answer



Yes, you would add a distance-constraint (known also as ball-socket joint) between the segments, and keep doing your normal physics on each segment.


There is a really simple and effective way to satisfy these constraints, which can be implemented in only a few lines of code.


The idea is that you reduce the error in a constraint partially, over and over for all constraints, in a loop. If you keep reducing the error by, let's say 20% in each iteration, it will eventually settle to a stable state where all the constraints are satisfied.


Note that it helps to keep the head position of the snake as-is, to make the tail follow the head, instead of vice versa.


So in pseudo code:


for i in range 1..10:
for each link between segments:
actual_dist = distance(body0, body1)
error = actual_dist - desired_dist

// fix 20% of the error in body0/body1 distance.
if body0 is not snakehead:
move body0 (0.1*error) units towards body1
if body1 is not snakehead:
move body1 (0.1*error) units towards body0

..which is all you need to have the tail follow the head.


NOTE: you get a slightly faster convergence, and more stable solution if you reduce the error in the links in a random order! So in the 10 times we scan over the links, we update them in a different order.


"Will Have Done" tense- meaning and examples


Looking for sufficient definitions and explanations of this tense, I noticed that one meaning will usually refer to something someone "will have done" as something that "will have been done\completed". While I do realize this is one independent reason to use this tense, I don't quite get a lot by a definition of a tense which uses the tense it attempts to define. It would really help me if someone could clarify the subject, including regarding similar forms, such as: Will Have: gone, finished, completed, ended...All(Or most V3 verbs).



Answer




This tense is called Future II simple



Usage



  • action that will have been finished by a future time


Example: Don’t worry, he will have repaired the bike by then.



  • supposition about what happened



Example: He will probably have noticed that his bike is broken.



Source1


Source2


camera - 3D Ray Casting / Picking


I am not sure if I should post this link, but I feel this falls into game development just as much as it does math. I have a ray cast's far and near values and I am trying to calculate the end point of the ray so that I can either draw a line to show the ray, or render an object at the end of 3d mouse position.


Here is my post on the stack overflow math site, if there is a problem with me doing this just close the thread. Thank you. https://math.stackexchange.com/questions/15918/help-with-matrix-mathematica




Answer



I think that you don't know 3D position of the clicked point, because otherwise it would be easy :).


So if you know 3D position of the clicked point in origin basis then you can calculate far and near points like this:


nearPoint3D = cameraposition3D
farPoint3D = cameraposition3D + (normalize(clickedPoint3D - cameraposition3D) * zFar)

The problematic part is clickedPoint3D. You can compute it nicely with help of view and projection matrices. As you are using opengl i suppose that you have them. view * projection matrix converts 3D points to the 2D screen space. You can use inverted viewprojection matrix and get matrix which converts 2D screen points to the 3D space.


pseudo code and some openGl:

//define matrices

Matrix4x4 g_CameraViewMatrix;
Matrix4x4 g_CameraProjectionMatrix;

//read projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(...); //your perspective function
glGetFloatv(GL_PROJECTION_MATRIX, &g_CameraProjectionMatrix.m[0]); //returns matrix as float array

//read view matrix

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLookAt(...); //you lookat function or whatever - NO translation,rotations or anything else for getting camera matrix!
glGetFloatv(GL_MODELVIEW_MATRIX, &g_CameraViewMatrix.m[0]);

//compute 3D position of clicked point
Matrix4x4 viewProjInv = (g_LightViewMatrix * g_CameraViewMatrix).getInverse();
vector4D clickedPointOnSreen = (x_screen,y_screen,1.0f,1.0f); // Z have to be between 0 - 1 and W have to be 1
vector4D clickedPointIn3DOrigin = viewProjInv * clickedPointOnSreen;
vector3D clickedPoint3D = clickedPointIn3DOrigin.xyz;


Note that you can use this to compute 3D points of zNear and zFar really easily:


vector4D clickedPointOnSreen = (x_screen,y_screen,1.0f,1.0f); // will produce 3D position of zFar
vector4D clickedPointOnSreen = (x_screen,y_screen,0.0f,1.0f); // will produce 3D position of zNear.

Isn't that algebra wonderful? :)


To learn something about projection matrix you can read this what-is-the-purpose-of-the-canonical-view-volume


Sunday, August 26, 2018

savegame - Unity - How To Save Some Variable WIth PlayerPrefs?


I have a small problem. in the game that I'm creating I created an array of items, each item includes a number of variables (cost, level, etc.). my goal is to save your own variables for each item, with the use of PlayerPrefs. These are my two scripts.


in this first script I create the array called (public Item_Manager [] items;), and in the second script initialize variables for each item dell'aray. I tried to save the values in the second script but then when I open the game again, all items are saved with the same variables.


Therefore, how can I do to save every variable of each item in the array with PlayerPrefs?



The variables are:


public float costo;
public float tickValue;
public float count;

This is the First Script


public class Proiettili_Per_Secondo : MonoBehaviour {

public UnityEngine.UI.Text bpsDisplay;
public Click click;

public Item_Manager[] items;

void Start(){
StartCoroutine (AutoTick ());
}

void Update (){
bpsDisplay.text = ConvertiroreProiettili.Instance.GetCurrencyInString
(GetPallottoleOgnISecondo (), true, false);
}


public float GetPallottoleOgnISecondo(){
float tick = 0;
foreach (Item_Manager item in items) {
tick += item.count * item.tickValue;
}
return tick;
}

public void AutoProiettiliPerSec(){

click.proiettili += GetPallottoleOgnISecondo () / 10;
}

IEnumerator AutoTick(){
while (true) {
AutoProiettiliPerSec();
yield return new WaitForSeconds(0.10f);
}
}
}


This is the second script


public class Item_Manager : MonoBehaviour {

public UnityEngine.UI.Text titolo;
public UnityEngine.UI.Text costo_;
public UnityEngine.UI.Text livello;
public UnityEngine.UI.Text valore_da_aggiungere;
public Color standard;
public Color caricamento;

public Click click;
public float costo;
public float tickValue;
public float count;
public string costo_stringa; ///NECESSARIO PER TRASFORAMARE IL VALORE COSTO IN UNO PIU CORTO (K, MILLIOM)
public string itemName;
private float baseCost;
private Slider _slider;

void Start () {

baseCost = costo;
_slider = GetComponentInChildren ();
}

void Update () {
titolo.text = itemName ;
costo_.text = (costo_stringa = ConvertiroreProiettili.Instance.GetCurrencyInString (costo, false, false));
livello.text = "Liv: " + count;
valore_da_aggiungere.text = "+ " + tickValue + "/Sec";


_slider.value = click.proiettili / costo * 100;
if (_slider.value >= 100) {
GetComponent ().color = caricamento;
} else {
GetComponent ().color = standard;
}
}

public void PurchasedItem () {
if (click.proiettili >= costo) {

click.proiettili -= costo;
count += 1;
costo = Mathf.Round (baseCost * Mathf.Pow(1.50f, count));
}
}
}

Answer



PlayerPrefs are not designed for saving scores. They are easily modifiable by the end user in a text file. Instead, you should serialize settings, replays, etc. that players have no motivation to hack.


Knowing that, this is how you save to PlayerPrefs:


int Birthday;

void Start ()
{
Birthday = 172589;
PlayerPrefs.SetInt ("My Birthday", Birthday);
}

For saving an array, you can serialize it as a string then save the string to PlayerPrefs. I.e.:


//Serializes an int[] into a string then saves it into PlayerPrefs
void SaveIntArray (string Name, int[] IntArray)
{

string SerializedArray = "";
string += BytesToString(System.BitConverter.GetBytes (IntArray.Length));
for (int i = 0; i < IntArray.Length; i++)
{
SerializedArray += BytesToString(System.BitConverter.GetBytes(IntArray[i]));
}
PlayerPrefs.SetString (Name, SerializedArray);
}

//Gets a string form player prefs and deserializes it as an int[]

int[] GetIntArray (string Name)
{
string SerializedArray = PlayerPrefs.GetString (Name);
byte[] SerializedArrayBytes = new byte[SerializedArray.Length]
for (int i = 0; i < SerializedArray.Length; i++)
{
SerializedArrayBytes[i] = (byte)SerializedArray[i];
}
int IntArrayLength = BitConverter.ToInt32 (SerializedArrayBytes, 0);
int[] IntArray = new int[IntArrayLength];


SerializationPosition = 4;
for (int i = 0; i < IntArrayLength; i+=1)
{
IntArray[i] = BitConverter.ToInt32(SerializedArrayBytes, SerializationPosition);
SerializationPosition += 4;
}
}

//Converts an array of bytes to a string

string BytesToString (byte[] bites)
{
string ret = "";
for (int i = 0; i < bites.Length; i++)
{
ret += (char)bites[i];
}
}

Alternatively, you can use PlayerPrefsX which has many more such extensions implemented.



If you're making a game for iOS, consider using UnityEngine.Social for saving scores which will save data on a Game Center server that will be unmodifiable except through your game's code.


mathematics - What is a good linear algebra book for game programmers?



I was told that I should start learning Linear Algebra in order to create good games with good physics.


I'm reading Linear Algebra book and it's completely foreign to me. The author starts out with solving linear equations (two equations, two variables) and I remember learning about that in school, but almost immediately he jumps into other things that seem to be taken directly from the Necronomicon.



What book can I read to learn some good math, but starting from the fundamentals?


Thanks a lot for the help.



Answer



Sergio you might want to aim more toward a Game Development math book like


Essential Mathematics for Games and Interactive Applications, Second Edition: A Programmer's Guide


Instead of the classical Linear Algebra you would learn in college. Also like Ron Warholic said, stating what your math comfort level is would better help us taylor a specific book.


terminology - Is the term "preposition phrase" replacing "prepositional phrase"?


I've noticed of late that the term preposition phrase is being preferred to prepositional phrase.



Is this a movement or an idiosyncrasy?



Answer



The people who started the use of preposition phrase appear to have done so on purpose, as snailboat explains in the answer to which she links. My impression is that wider use has been not so much a movement as bare movement, sort of like Brownian movement. Perhaps we could call it a drift.


My own opinion is that using both X phrase and Xal phrase, with distinct meanings, is a useful tool. The general principle involves a distinction between structure and function. That is, we (meaning me, now that I have grokked the idea) use X phrase to designate a sentence constituent which is built on an X (headed by X is the jargon), and Xal phrase to designate a sentence constituent which acts as an X.


Consistently drawing this distinction would avoid the sort of confusion which is evident in the commentary to this question (which I suspect is what prompted your question). In the sentence “Jane is in the meeting room” the phrase in the meeting room is structurally a preposition phrase; functionally, however, it acts either as an adverb according to traditional grammar or as a predicate complement according to newer grammars, and would accordingly be called either an adverbial phrase or an adjectival phrase, depending on your sectarian posture.


What then would a prepositional phrase be? That's illustrated by the other example sentence in that question, “Jane, along with other students, is in the meeting room”. There’s room for all sorts of entertaining theological controversy in that sentence, but I’m sure that some people would regard the collocation along with as a single consituent acting as a sort of compound preposition. That would be properly described as a prepositional phrase.


ellipsis - Why is a preposition sometimes optional?


This question arises after seeing this thread.


Consider the following sentences -





  1. There is no point discussing this here (Between "point" and "discussing", there is a "in" and that is optional. And I am omitting it purposefully for asking my doubt)




  2. Do you see any point in filling up all the forms?





  3. There is no use filling up the forms. ("using "in" after "use" is optional here)




  4. What is the use of filling up these forms?





My question is -



Why in some sentences omitting prepositions like this is optional and why in some cases placing preposition is a must?




Saturday, August 25, 2018

word meaning - Tomato ketchup Vs Tomato sauce


Dictionaries did not help me. Collin's writes tomato sauce = tomato ketchup but not vice versa. There tomato ketchup is ketchup flavored with tomatoes. Furthermore, ketchup is sauce!


MM says ketchup is sauce and so does OALD. Times of India has good note on that but is understood and written by a non-native and so not sure. Wikipedia says ketchup is a table sauce. Phew!



What I understand (looking at the ingredients) - tomato sauce contains no garlic/onion in any form whereas tomato ketchup has them.


Enlighten me please.



Answer



Strictly speaking, the dictionaries are correct: Tomato ketchup is a form of tomato sauce, since a sauce is simply "a liquid, semi-solid, or cream food served on other foods".


Ketchup is very specifically a sweetened and thickened tomato puree that usually contains vinegar, onions, garlic, and other spices. The exact composition varies between manufacturers, but it always contains sugar and almost is always thickened, and it contains no lumps or non-blended components. The tomatoes are usually cooked completely before blending. It is most often eaten with fried foods, meat loaf, and hamburgers.


In American English, "tomato sauce" is generally distinct from "ketchup". "Sauce" would be the kind of tomato product you would eat with spaghetti, or put on pizza, or eat with chicken parmigiana. It generally does not contain much added sugar or other "sweet spices", and it may or may not be completely blended. The tomatoes may or may not be cooked before blending. (Wikipedia also notes an "incomplete" form of tomato sauce, which is simply blended tomatoes with no other additives other than salt. It is used as a base for more complete sauces and is not intended to stand alone.)


Ultimately, in American English, the difference comes down to application. Ketchup will rarely be eaten with pizza or spaghetti, and few people would eat tomato sauce with fries or hot dogs. It's not so much a matter of people deliberately distinguishing the words as that the distinction arose organically.


grammar - postpositive participles


My grammar book told me that when a participle functions as an adjective, normally it should be used before nouns. But I still saw some sentences like:


The experience gained will be of great value to us.


They decided to change the material used. (And they also said, the meaning is different with the prepositive"used" here means something which is used nowadays, but the prepositive one means second-hand)


When can we put participles after nouns and these different meanings of participles can be predicatives?




c++ - 2D Circular View/Background Wrapping SDL for Game


In the games such as Defender (1980 arcade) and Defcon, the player can move/scroll in one direction infinitely because the level/terrain simply wraps over and over again(like if it was wrapped around the side of a cylinder).


I am more interested in the wrapping mechanics of Defcon which wrap(on the x-axis) and zoom the entire level. Here is a link to view the game.


To make images(such as a background) wrap is it a per-pixel approach? Is there a function? What methods are there to achieve the circular wrapping of a level?



Answer



When I have used a repeating background image, I used two copies of the image side by side and scrolled the pair. When one gets to the edge of the screen, reposition it off the screen.


How do I implement parallax scrolling in 2D?


Suppose I have three layers: a foreground, an intermediate-ground and a background. What is involved in using these three layers to create parallax scrolling?



Answer



Divide the position of each layer by the “distance” you want it to have from the camera.


For example: Create a couple of variables to represent the camera position, cameraX and cameraY. Set these to equal the position of your character, possibly adding on a bit extra in the direction of movement.


The main layer would just be positioned at


mainLayer.x = -cameraX;


the middle layer at something like


middleLayer.x = -cameraX * 0.5;

and the far layer at


farLayer.x = -cameraX * 0.2;

Change the constants as needed.


c++ - How can I improve my collision detection's performance?


I'm new to programming and want to speed up the collision detection in my C++ 2D platformer game engine.


Currently, only the player's collision detection works: Every frame, the player's update function iterates through every level tile (which is pretty many) and checks if the player hitbox collides with it.


I may be way off on this, but this seems like a really chunky way of doing it. Is this bad practice? If the level gets large enough, is iterating through this list going to take forever like it seems it should?


My second question builds off of that: If I start adding for example enemies into the engine and give them a similar method for collision detection, can I expect performance drops? I'd like some insight from more experienced people on a better way of setting this up. I would just imagine that having ~20 enemies on the screen all iterating through all possible objects for collision with a list could get slow fast.



Answer



Preliminary warning: Optimisation is a dangerous cast-from-life-type magic. You should always optimise as late as possible, because machine time is cheap. Obfuscate your code for performance only when you know you need to. Many small games manage just fine with the simple method you've described.





That said, here's the news:


The bad news is that you're right: Giving larger inputs to any algorithm will eventually slow it down. Bigger problems are harder—that's a physical certainty.


The good news is that different algorithms slow down at different rates. The rate at which an algorithm slows down with respect to the input size is called its computational complexity.


I'll first explain computational complexity theory (what efficiency is) then some techniques to speed up your specific problem.



Let's start by making a slow algorithm, in a way no sane person would do it, because it's easier than making a fast one and better illustrates how to measure an algorithm's efficiency.


The way you're doing it, iterating through a list to find whether any tile collides with your player has linear complexity (often written as O(n)-complexity or order-n-complexity). This means that if you double the size of the input (how many tiles you have), that also doubles the time the algorithm takes to run.


Iterating over a...
...1-element list: 1

...2-element list: 1 2
...3-element list: 1 2 3
...4-element list: 1 2 3 4
...5-element list: 1 2 3 4 5
...6-element list: 1 2 3 4 5 6
...7-element list: 1 2 3 4 5 6 7


Iterating over a large list of n elements this way has complexity O(n).


Some algorithms slow down even more easily: For example, imagine if every time you wanted to access one of the tiles in your list, you had to start over and iterate to that tile all over again from the start of the list. (No sane programmer would actually do this, but hey, it's a possible algorithm.)


Iterating over a whole list of different lengths would cause reads something like this:


Dumb-iterating over a...

...1-element list: 1
...2-element list: 1 1 2
...3-element list: 1 1 2 1 2 3
...4-element list: 1 1 2 1 2 3 1 2 3 4
...5-element list: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
...6-element list: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6
...7-element list: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5 6 7


That blew up pretty fast in comparison. Given a list of n elements, this algorithm takes 0.5 * n * (n + 1) time. In computing, we often shorten this by calling it O(n ^ 2), because the n-squared term dominates as the list grows.


I'm sure we could come up with an even dumber way of iterating over a list with an exponential or even factorial complexity. Let's not do that. Instead, let's go to the other extreme.




Can we find the collision response of a player character with a large number of static walls in constant time? This is the fastest possible time complexity: It would mean taking the same amount of time regardless of the input size.


Yes! We could precompute and store every possible position that your player character could possibly be standing at and the appropriate precalculated collision response, in memory.


Assuming your game world is 2000 by 1000 pixels large and that your player and walls are positioned at integer coordinates, then you'd have to store a


struct CollisionResult {
int collisionResponseX;
int collisionResponseY;
}

for every possible position your player could be in (struct CollisionResult[2000][1000] collisionResponseCache) and you'd have a complete and immediately queryable cache of what collision to expect when a player is in any position.


This is a constant time algorithm: Indexing into an array (something like collisionResponseCache[player->posX][player->posY]) is just as fast for every possible input—mere milliseconds.



We've traded memory space and flexibility to gain time complexity.


How much memory space? Assuming your machine has 4-byte integers, that big array would take up 2000 * 1000 * 2 * 4 = 16000000 bytes of space—that's 16MB. That's quite a lot of memory and it increases linearly with the size of your game world, though it's not too bad for a modern PC with gigabytes of RAM!


How much flexibility? This constant-time method assumes all of the things you want to test for collisions against are present and static (and hence precomputable). This is often limiting, as it prohibits moving enemies, collectibles, breakable walls and such.



A better algorithm would allow more flexibility (changing inputs) but still be faster than linear time. How might we do that?


Consider a two-dimensional game world with some game entities in it.


simple 2D world with square entities


We could easily double the collision detection algorithm's efficiency by keeping two lists of objects instead of just one: A list for objects on the left half of the level and another for the right half:


game world divided into 2 buckets


Whenever an object crosses the boundary, we'd move it to the other list. This way, we only need to check for collisions against the objects in the list corresponding to the side of the stage the player is on.



We can take this further by introducing two more lists and splitting the level in four instead.


game world divided into 4 buckets


Or into twelfths. Hundredths? We can parametrise this as we like, to control how much flexibility and memory we want to trade for speed. Making each list represent a 1×1 area (a single pixel) makes this essentially degenerate to the "store absolutely everything"-approach above.


many different grid sizes


This is the gist of a spatial subdivision technique called spatial hashing. The details are a little more complex, as you have to account for entities' sizes (they might be in many cells at once). C++ implementation details are the domain of another question.


A quadtree works in a similar manner, but it subdivides cells only as needed:


a sample quadtree
Many thanks to David Eppstein of Wikipedia! The image page includes Python source code!


If your game objects are relatively sparse, quadtrees may be significantly faster than a spatial hash, so they're also worth investigating. Again, implementations and guides exist that I won't replicate here, but this is the gist of it.


Friday, August 24, 2018

architecture - How to edit key-value pairs (like a Dictionary) in Unity's inspector?



I have a spell system I am creating, the principle is as follows:



  • Each spell is an autonomous prefab. It contains a script with some properties (base damage, duration...) that can be modified in the inspector.

  • I have a Spell enum listing all possible spells in the code, which is used in the game logic

  • When I want to cast a spell, I need to be able to get this spell's prefab to instantiate it and read its informations

  • Each actor (be it players or enemies) needs to have a list of possible animations for the spells


The problems with how I am trying to implement are:



  • For listing each actor's animations I could use a Dictionary, but dictionaries aren't supported by the inspector which makes it hard to easily edit multiple actors type.


  • I need some way to easily access a spell prefab from the corresponding enum. Here too I could use a dictionary but I can only reference to prefabs in the inspector, not in code, meaning I wouldn't be able to fill this dictionary


I am looking for a way to easily associate my spells enums to the corresponding prefabs and animations



Answer



One quick way to get key-value pairs in Unity's inspector is to define a serializable entry class, and then use an array or List<> of them. eg...


public class SpellAnimationMap : ScriptableObject
{
[System.Serializable]
public class SpellAnimationEntry
{

public Spell spell;
public AnimationClip animation;
}

public SpellAnimationEntry[] spellAnimations;
}

Automatically, this will give you a resizeable list in the inspector where you can enter the key and value, without needing to write a custom inspector.


The result looks like this:


auto-generated inspector



(One trick: if the serialized entry class contains a "Name" field, that string will be displayed instead of the bland "Element 0" headings. Useful if you have more complex data you want to be able to navigate efficiently.)


Making this a ScriptableObject allows you to treat it as an Asset shared between entity types/instances that need the same animation set, avoiding overhead of duplicating the list for each. (Other classes tend to be serialized per-instance in Unity). To go this route, you'll need to add a small editor script to let you create instances of these in your Assets folder.




Edit: now it's even easier - you can just add this attribute above your ScriptableObject:


[CreateAssetMenu(fileName = "fileName.asset", menuName = "Some Folder/Menu Label")]

This puts the ScriptableObject into your Create menu, like so: Screenshot showing a customized Create menu in Unity




You can optionally make the array private and serialized so that it still shows up in the inspector, but add a public Dictionary (or private dictionary with a public GetAnimation(Spell spell) method) for clients to consume for more efficient lookups. In its OnEnable() method, the SpellAnimationMap can iterate through its inspector-populated array to build this dictionary once, again sharing the benefit between all client instances. (Note that OnEnable() is also called in the editor when the asset is first created, so be sure to check that your array is non-null before you try to read it)


Finally, you can add as much into this entry datatype as you need. It could include the prefab too, for instance, or any number of other bits of data you want to link to the spell key.



It's also possible to write custom inspectors to populate Dictionary<,> fields directly, but the impression that I get is that it's fussy to get working smoothly.


sentence meaning - What does "black sheep wall" mean?


It's a cheat code from StarCraft to reveal entire map, but different from other cheat code, it's really hard to understand.


I can understand most cheat codes:



  • show me the money - get a lot of mine and gas

  • whats mine is mine - get some mine(a pun)

  • breath deep - get some gas


...



So, what does "black sheep wall" really mean? Is there a story behind it?



Answer



Black sheep wall itself is not an idiom or saying in English like many of the other cheat codes.


However, a black sheep is a family member who does not live up to the parents' or family's expectations. Or one kid who "goes bad" while all the other kids do great. It could be that the wall lets you see all the black sheep (i. e., the aliens).


There is a song "Black Sheep Wall" by The Innocence Mission. The album that the song is on was released in mid-1989, years before Starcraft was first released, March 1998. Some Starcraft fans say the cheat code refers to the song title. The song is, here on YouTube and you can Google the lyrics yourself.


There is now a band called Black Sheep Wall that is allegedly named after the cheat code.


past participles - Haven't {eaten / ate}?


While chatting with somebody, I first used haven't eaten, then I thought that it was wrong, and switched to haven't ate.


Apparently, haven't ate is the one which is wrong.


Can someone explain the logic behind this? Verb tenses are still something I confuse a lot.



Answer



The principle parts of the verb eat are:




eat     infinitive and present
ate     past
eaten   past participle
eating  present participle



Accordingly, perfect constructions are formed with have + eaten:



I have eaten, you had eaten, he will have eaten, &c




Passive constructions are formed with be + eaten:



We are eaten, you were eaten, they will be eaten, &c



Progressive (continuous) constructions are formed with be + eating:



I am eating, you were eating, she will be eating, &c



You will occasionally hear et for the past, and even for the past participle but in US speech these are strictly non-standard dialect forms.


word usage - Confusion using articles (A ,an ,the)


I am making a test where I am asked to add the missing words.




[...] chair is [...] useful piece of furniture.



I would have said that a is the missing word in both the cases, but the test says the words I should have added are the and a respectively.



[...] last time I saw [...] bear, I was travelling in [...] Europe.



I would have added: nothing, a, nothing. The correct answer is: the, a, nothing.


Why is the the correct article to use in both the sentences?



Answer




1. In the first example "the" is used because of generalizing. When you generalize about something (an object, an animal), you use the definite article before it if it is a singular countable noun. Some other examples would be:



The horse is a mammal.


The telephone is a useful invention.



Notice than uncountable nouns are used without an article in this case:



Milk is good for you.



2. In the second example "last time" sounds similar to "last week" or "last month" and that is why many people would not use "the". Compare, however, these two sentences:




He said something completely different last time.


The last time we met he said something completely different.



In the first example"last" means "previous, the one closest to the present", and is similar to the use in "last month, last week". In the second example we use "the" because it is the last in a specified period of time or within a specified group of events. The difference would be more obvious here:



We met last Friday.



This is the most recent Friday.




The last Friday he was here we went to the museum.



This is not the most recent Friday, but the Friday, which was last of all the Fridays he was here.


How do I handle Isometric collision detection?


I would like to make an isometric run-jump style platformer. The player should be able to jump on top of platforms above the floor, hit the side of objects etc.


I'll be using a 2D game engine so I wouldn't like to emulate full 3D collision for dimensions I'm not using.


I'm thinking objects in the game should be placed using: X, Y, width, height, and Z for depth.


Using those values, how should I detect collisions?




c# - How to rotate within a fixed interval in Unity?


I have very recently started to learn Unity.


I'm trying to write code that will make a character swing a flag. I want to use this object and rotate the arm up and down. So I need to make it rotate up and down with within 30 degrees.



This is my attempt but it simply keeps on turning. How would I make the hand rotate in motion within the interval [-30, 30] degrees.


private GameObject myobject;
public float timeElapsed =0;
public float delay = 3.0f;
float OO = 0.0f;

void Start () {
myobject = GameObject.Find ("rightarm").gameObject;
}


void Update () {
timeElapsed += Time.deltaTime;
Debug.Log (timeElapsed);

if (timeElapsed >= delay) {
OO = 30.0f;
timeElapsed = 0;
if (myobject.renderer.enabled == false) {
myobject.renderer.enabled = true;
}


myobject.transform.Rotate (OO, 0.0f, 0.0f);
}
else
{
myobject.transform.Rotate (-OO,0.0f, 0.0f );
}
}


unity - Unity2d: orthographic camera and z-axis?



I wonder if anyone can help with an explanation of the z-axis and using unity with 2D with an orthographic camera.


Up until now i have only been modifying the x and y values of game objects, thinking this is the correct way. i thought the Z axis didn't exist in 2D space (i.e. unity 2d with orthographic camera) but I do notice that the orthographic camera is placed at -10 on the z axis, if i change this value then the camera disappears. I sort of began to accept that.


Now I cam to a point where I wanted to rotate something, and I notice that rotating eithe on the z or x axis, doesn't seem to do anything, only on the z-axis, there is that z-axis again !


Can anyone tell me when i should be worrying about the z axis in unity using 2D games.


It seems now that it is more important than I once thought :-)


Thanks in advance.




licensing - What happens if I make more than $100k with the free Unity license?


If an indie game developer makes more than $100,000 using the free version of Unity, what happens to the money that goes over $100k? How will Unity people come to know how much money they are making?


What precautions should I take just in case a game is a great success?



Answer




Update: In June 2016, Unity revised their business model. They no longer offer permanent licenses, only subscriptions. However, they now offer a cheaper plus-version without the unprofessionally-looking Unity splash screen but with a revenue limit of $200,000. They also made some changes to the license agreement which required an update to this answer.






The Unity software terms regarding the differences between the personal, plus and pro version are pretty clear: When your company makes a gross revenue (not profit!) of more than $100,000 per year, you need to subscribe to the plus-version ($200,000 limit), pro version (no limit) or enterprise version (no limit):



Unity Personal may not be used by:



  • a Commercial Entity that has either: (a) reached annual gross revenues in excess of US$100,000, or (b) raised funds (including but not limited to crowdfunding) in excess of US$100,000, in each case during the most recently completed fiscal year;

  • a Non-Commercial Entity (this means academic and governmental entities as defined below) with a total annual budget in excess of US$100,000 (for the entire Non-Commercial Entity (not just a department)) for the most recently completed fiscal year; or

  • an individual (not acting on behalf of a Legal Entity) or a Sole Proprietor that has reached annual gross revenues in excess of US$100,000 from its use of the Unity Software during the most recently completed fiscal year, which does not include any income earned by that individual which is unrelated to its use of the Unity Software.




The upgrade becomes required at the end of the fiscal year, because that's the way revenue is calculated according to the license conditions. As long as you don't subscribe to licenses for all your Unity users, you are obligated to stop using Unity. You are still allowed to sell your games, but you are no longer allowed to update them, even when you don't need the Unity editor to make updates:



During the term of this Agreement, you expressly acknowledge and agree that if you are a Unity Personal or Unity Plus user and the above thresholds are exceeded, then you may no longer use that tier of the Unity Software, and you must either: (a) purchase Unity Plus (if eligible) or Unity Pro; or (b) destroy all copies of the Unity Software in your possession or control, and cease updating Your Project Content. Unity will monitor your compliance with and enforce these restrictions and requirements including but not limited to monitoring the number of downloads of Your Project Content and any available revenue estimate data.



What happens when you don't? When your games are that successful, you will likely not stay under the radar. When Unity Technologies suspects that you make more than $100,000 with the free version of their product they might sue you. During that lawsuit you might be forced to show your books to prove how much revenue you made and how many people you had working.


The court will decide what happens with any of the money above $100,000 you received from sales. Depending on the jurisdiction in which you are sued and their interpretation of the applicable laws and the EULA they might rule that you are entitled to it, that Unity Technologies is entitled to it, or that the sales are void and you need to refund it to your customers. Ask your lawyer what they consider the most likely outcome (don't tell us you can't afford one when you make over $100,000 a year).


debugging - How do you get useful data from playtesters?



There are a few types of feedback you can get from playtesters, and I wonder how to best gather data for each of them...




  1. Crash Reports. When my C++ game crashes while someone is playing it, how do I best make sure that I know about it and even better... what caused it? Even getting something as simple as the file and line number which caused a crash would be incredibly helpful.





  2. Design Feedback. When a play tester is playing the game, how can I figure out if they are having fun, why they are having fun, why they aren't having fun, and what we should spend time adjusting?





Answer



I'm assuming you're talking about on-site playtesters and not internet beta testers.


Rule #1: Don't help them. Frustration should be the top thing you should be checking for. The ideal situation would be a two way mirror with your team on one side and the playtester on another with one video camera on their face and another on the screen. Obviously this isn't feasible for most people, so do the best you can. Just having your designers sit and watch where people get stuck is very useful information. You're not going to be standing over their shoulder when they take the game home, so you giving advice on how to pass certain sections isn't going to give you the information you need. Edit: another way of putting it is this: Don't think they're "Playing it wrong"


Rule #2: Don't give them what they want. After a playtest session you have some kind of questionnaire that they fill out. The specific suggestions they have are usually not wise to take at face value. Usually there's some root cause that is triggering most responses and they just don't know how to express it. If you can figure that out, you'll be better off doing it. Although at the moment I'm having trouble coming up with specific examples.


Rule #3: Data is king. If you can (and this is really another wishlist item, honestly), track everything you can. Track where players die. Track where they run out of ammo from a specific gun. Track what pickups they miss. Track what upgrades they buy. Track what enemies do damage to them. Obviously these are FPS-specific examples, but I'm sure there are domain specific ones for whatever game you're doing. If everybody's doing something or not doing something, those are usually areas that you should spend a little more time looking at.



Basically, you don't care what player's think. You care about getting raw numbers for what players do. You need virgin eyes to see your game and tell you what makes them frustrated and what they're being led to do.




For crashes, investigate minidumps. They're not perfect, but are a very useful tool to figure out where crashes are.


Also consider a built-in bug reporting tool. Something where the user can take a screenshot , add a description, and email it to someone automatically from inside the game. Ideally with a snapshot of the world (i.e. quicksave or some kind of memory dump) if your game supports it.


Thursday, August 23, 2018

path finding - Techniques for (literally) cutting corners on square grid maps


My game involves a level with deformable terrain and units that can travel in any direction but are slowed down by uneven terrain. Normal A-star should work fine in most cases, except on flat land where no matter how the general purpose pathfinder worked it would not send units on a direct path. Theta-star would work if the entire level was fairly flat, but would be much slower if it initially had to take uneven terrain into account.


I think a Manhattan-distance base A-star algorithm would be fast and give a good enough hint to allow other path finding or steering algorithms to take over, but I'm not sure what type of algorithm to use to look ahead and decide when to abandon the path, take a more direct route, and where to jump back on the path later.


(Theta-star seems like it would be too inefficient if it was adjusted to take things like slopes, obstacles, or roads into account. See the solution proposed to the comment about avoiding minefields at: http://aigamedev.com/open/tutorials/theta-star-any-angle-paths/ )


Edit: I did not mention that I already implemented and tested A-star on a similar grid. (I think I accidentally deleted something in this question.) Some of the more obvious cost/heuristic functions I considered just don't result in realistic paths on a grid when an obstacle blocks the most direct path (basically when path-finding is useful) (example pictures). The change to the cost function used by the Theta-star algorithm seems like an ideal solution (considering the constraint of using a grid), but it makes the assumption that tiles have the same travel costs (and it takes much longer).


My original reasoning behind using Manhattan distance was to outsource the "corner cutting" algorithm from the path-finding algorithm, since it was more important to have a fast path-finding algorithm in case the obstacle layout or terrain changed. It makes more sense to do the "corner cutting" algorithm once when the unit arrives than on every permutation of every search of path-finding algorithm (the results of which may end up being scrapped anyway.) A four-neighbor search with Manhattan distance is also interesting because you can see boxes of alternate paths and identify right triangles formed by the original path and the shortest path.



A better question would have been "What is a fast way to identify shortcuts in a path with 90 degree turns?"




pronunciation - How to Improve Intonation?


Anyone who has successfully improved intonation in a non-native environment?


I consider myself as an expert of English grammar as well as when it comes expressing myself in speaking. At least that is what most of the native speakers I have been lucky to have a chat on Skype say. The area of improvement I am constantly suggested is 'intonation'. I do realize that my voice does not go up and down like it should. It's rather plain and dull. I figured it's partly due to the fact that I get nervous and start speaking faster. When I speak slower the intonation is relatively good but still not good enough.


Now I have my IELTS academic exam next month and I want to work on this aspect of my speaking. I am no the way to come somewhere near a native level. I just want to improve enough to not sound so bland as I do now.


The only possible way to improve intonation I have come across are YouTube videos where you repeat what is being said in the video. Has anyone tried that?


If you have any other suggestion to improve intonation, please share.



Answer



I would rather suggest you to 'imitate'



If you go by the book, you have to study and practice too.


Intonation is the later part of syllable stress, which talks about the smallest units of sound in a word. Which is way harder learning until you get here.


Imitating the native speakers is the easiest way of learning an accent and this is exactly the way you learnt your own language.


Here are a few things to learn and have fun too.


Watch Movies, Listen to the narrators on Net.Geo (I love Morgan Freeman), find yours. Sing English songs. Talk to people who speak better than you. Last and the most important 'love this language' it's fun.


algorithm - How to implement an intelligent enemy in a shoot-em-up?


Imagine a very simple shoot-em-up, something we all know:


shoot-em-up 1


You're the player (green). Your movement is restricted to the X axis. Our enemy (or enemies) is at the top of the screen, his movement is also restricted to the X axis. The player fires bullets (yellow) at the enemy.


I'd like to implement an A.I. for the enemy that should be really good at avoiding the players bullets. My first idea was to divide the screen into discrete sections and assign weights to them:


weighted shoot-em-up



There are two weights: The "bullet-weight" (grey) is the danger imposed by a bullet. The closer the bullet is to the enemy, the higher the "bullet-weight" (0..1, where 1 is highest danger). Lanes without a bullet have a weight of 0. The second weight is the "distance-weight" (lime-green). For every lane I add 0.2 movement cost (this value is kinda arbitrary now and could be tweaked).


Then I simply add the weights (white) and go to the lane with the lowest weight (red). But this approach has an obvious flaw, because it can easily miss local minima as the optimal place to go would be simply between two incoming bullets (as denoted with the white arrow).


So here's what I'm looking for:


shoot-em-up total destruction



  • Should find a way through bullet-storm, even when there's no place that doesn't impose a threat of a bullet.

  • Enemy can reliably dodge bullets by picking an optimal (or almost optimal) solution.

  • Algorithm should be able to factor in bullet movement speed (as they might move with different velocities).

  • Ways to tweak the algorithm so that different levels of difficulty can be applied (dumb to super-intelligent enemies).

  • Algorithm should allow different goals, as the enemy doesn't only want to evade bullets, he should also be able to shoot the player. That means that positions where the enemy can fire at the player should be preferred when dodging bullets.



So how would you tackle this? Contrary to other games of this genre, I'd like to have only a few, but very "skilled" enemies instead of masses of dumb enemies.



Answer



I think your basic idea is sound, but it is not analogue. You need an analogue field of value that runs across the screen. So, 1D diffusion gradient, from which you can derive a value at an exact point on that line, on the fly. Diffusion gradients are cheap and can be used by multiple enemies at once, as they describe the environment, and not the entity's view of it (a bit like radiosity lighting) -- probably why you've opted for the approach you have in your question. This gradient should be relatively smooth, so as to evoke organic movement from the enemy, and obviously updates as your gamestate does. Perhaps moving average?


The gradient should combine:



  • Proximity

  • Velocity

  • Breadth of bullet

  • (optionally) Position of targets (players)



For dodging, we have to be able to find a solution accurately whenever a solution exists. Such is the case whenever there is a gap small enough for the enemy to dodge through. That is, you can only do what you can do, so the gradient approach will work no worse than any other approach in this sense, I'd say.


The diffusion gradient should push the enemy towards local optima (being the peaks in the graph) with less imperative to move, the closer we are to a local minimum, hence a diminishing returns effect on dodging. This opens the door to more intelligent decision-making as to when the enemy has a good opening to fire.


If the need to fire is greater than the need to move, then do so; your code may also determine this by how much they differ. You can implement this as part of the base graph, in which case the player position reduces the surrounding values in the graph (assuming enemies gravitate to the lowest point), which combines all decision-making into one graph, or you can keep the "desire to fire" graph separate from the main "desire to dodge" graph, which will offer you more direct control.


IRL, I wouldn't bother dodging a projectile until it's within a distance which I know, at my top dodging speed, is starting to become difficult to avoid. First hand experience from throwing stones as a lad. A bullet at x distance travelling at velocity y has the same danger rating as a bullet at 2x distance travelling at 2y. So this needs to be factored in correctly.


Ways to tweak the algorithm for enemy difficulty include



  • introducing a latency on updates to the graph (Born Too Slow)

  • introducing random, localised innaccuracies into the graph

  • simply not having enemies obey what the graph tells them, over a sequence of updates (say 1 to 10 frames) due to sheer AI laziness.



Again, you can either implement all the factors into one graph (less control, and less useful for multiple enemies), or into several graphs which you look at together to get the results (more modular, probably works better for multiple enemies). It's hard to be more specific, as there are a lot of directions you can take this approach.


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