Thursday, February 28, 2019

nouns - Why is 'for examples' wrong?


If you want to take an example or several examples, you use the phrase 'for example,' not 'for examples.' Though the word 'example' is a countable noun, why is 'for examples' wrong?




terminology - What is the difference between an "API," a "framework," an "IDE," and an "engine?"


I am just starting out trying to learn to develop games. At first I thought C++ and OpenGL were the tools a beginner would start out to make a game, but quickly found out the OpenGL was just a API for graphics. Then I thought C++ and SFML were what I needed to learn to make a game, but found out the SFML was a media framework that could be used to make games but wasn't a game engine.


I don't want to use a software that does all the work for me, I want to code my own game, the way a game programmer would. I don't understand the difference between a IDE, framework, API, and a engine; What separates them from each other? Do some game programmers use the SFML framework, while other programmers use a game engine?



Answer



An API (Application Programming Interface) is an interface; a set of methods you use to interact with an object or set of objects to do something. Example: OpenGL, for 3D graphics.


A Framework is a step up; it's not only a set of APIs, but a way to think about and solve problems. Example: SFML, for media. It gives you graphics but also input handling and other auxiliary APIs.


A Game Engine is more specialized than a framework; it's a framework very specifically targeted to make games, and usually only games of some kind. It usually includes a lot of authoring tools around it, like model editors or importers, etc. Example: Unreal Engine. Lets you make 3D shooters. While you can use SFML to make a 3D shooter, you can also use it to make a video player. With Unreal Engine you make 3D shooters.


An IDE is unrelated to all these. It means Integrated Development Environment, and it's a step up from a plain text editor. It produces source code files which are text files, but in general it has some sort of integration with the compiler, offers wizards to automate parts of writing the code, and so on. Example: Visual Studio, Eclipse.


About "coding your game", unless you're experienced, I'd start with a Game Engine. You can write code to customize how it works and what it does, but it will save you a lot of work towards "your first game". Later you may want try writing your own Game Engine, maybe building on top of a Framework. And if you really like it, you can build your own Framework based on system-level APIs (OpenGL, Direct3D). It can be incredibly rewarding and a great learning experience. FWIW, I was quite experienced as a programmer when I started my Game Engine, but I built it on top of SDL; later I replaced the SDL layer with my own Framework.


word choice - Which article to use: 'the' or 'a'





  1. We adopt the approach under which the ...




  2. We adopt an approach under which the ...





  3. We consider the scenario where ...




  4. We consider a scenario where ...





Suppose that I say nothing about the approach or the scenario before there corresponding sentences. However, suppose that the scenario is known in the literature.


I am a bit confused about the article usage here since I am explaining/clarifying things about the approach (resp. scenario) after under which (resp. after where)


Question: (a) which one between 1 and 2 is correct ? (b) which one between 3 and 4 is correct ?




Answer



It seems you understand that the definite article is used when you are talking about a specific case, and the indefinite article used when talking about a non-specific or general case. Here, however, since you're introducing something new, both mean almost exactly the same thing. There is only a slight different in nuance, implying specific or non-specific, but the essential meaning is unchanged either way.


Depending on context, "the" is slightly more confident and assertive, than "a/an". "The" is more common in things like advertising because it implies that the service or product is the specific one you will need:



We have created the website that will answer all your English-language questions


We have created a website that will answer all your English-language questions.



It's not always appropriate to be too assertive, especially with things like scientific or technical papers where many approaches are possible. In your example, "the" is appropriate to draw focus to this one, specific approach. "A" suggests that you might talk about other approaches later, or that you want to imply the approach is generic. Again, both mean much the same thing and any additional meaning will depend on context.


If you add any modifiers to the noun, usually one or the other will work better, but this varies:




We determined the best approach where ...


We defined a new approach where ...



articles - "the" before general concepts


Take a look at these two sentences:



There are problems for students living away from the family.



Computers play a very important role in education nowadays.



Comparing them, I wonder why in the second one, 'education' is not preceded by 'the'.




Wednesday, February 27, 2019

Using bare infinitive after 'does'



All he does is watching TV.



I said this sentence and my native friend corrected me and said 'you need to use bare infinitive here'




All he does is watch TV.



Why is this right while the other is false? If I change the placement of the complement and subject, I will have this sentence:



Watch TV is all he does.



Shouldn't it be 'watching TV (or to watch) is all he does'?


I searched for it online and I couldn't get anything. Is there a rule that I'm missing? When do they use bare infinitive after 'to be' verbs?


Thanks




Answer



Your friend's correction was accurate. A native speaker would say



All he does is watch TV.



Your proposed reversal of complement and subject is also correct: it would indeed be expressed as



Watching TV is all he does.



"To watch TV is all he does" is grammatically correct, but you would almost never hear it in normal speech.



Unfortunately, there is no universal rule governing this usage. However, "does" is almost always followed by the bare infinitive in everyday usages like this one, even when another verb (like "to be" in your example) comes between them.


A thread at the Wordreference.com forum discusses this usage.


The omission of "to" before a complemental infinitive ("to watch" in your example") is expected when the finite element of the first verb is a form of "do" or a modal verb with "do" as dependent:



All he does is watch TV.
All he did was watch TV.
All he could do was watch TV.



The omission of "to" is optional when the finite element of the first verb is a non-modal verb with "to do" as its complement:




All he wants to do is (to) watch TV.



Like many things in English, this initially confusing construction will become more clear as you use the language in everyday conversation and reading.


Verbs with neither "-ing" nor "to"



I heard a phrase, a moment ago,




We will see this continue.



Why neither continuous tense nor "to" was used for "continue"?



Answer



With verbs of perception the complement is the bare infinitive (without "to") or the present participle


I heard the phone ring|ringing.


I saw the car skid|skidding on the ice.


I smelled the wood burn|burning.


She heard the baby cry|crying.


The fans watched the teams compete|competing.



They felt the ground quake|quaking.


c++ - Bullet Physic: Transform body after adding


I would like to transform a rigidbody after adding it to the btDiscreteDynamicsWorld. When I use the CF_KINEMATIC_OBJECT flag I am able to transform it but it's static (no collision response/gravity). When I don't use the CF_KINEMATIC_OBJECT flag the transform doesn't gets applied. So how to I transform non-static objects in bullet?




DemoCode:


btBoxShape* colShape = new btBoxShape(btVector3(SCALING*1,SCALING*1,SCALING*1));

/// Create Dynamic Objects

btTransform startTransform;
startTransform.setIdentity();

btScalar mass(1.f);

//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);

btVector3 localInertia(0,0,0);
if (isDynamic)

colShape->calculateLocalInertia(mass,localInertia);

btDefaultMotionState* myMotionState = new btDefaultMotionState();
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);

btRigidBody* body = new btRigidBody(rbInfo);
body->setCollisionFlags(body->getCollisionFlags()|btCollisionObject::CF_KINEMATIC_OBJECT);
body->setActivationState(DISABLE_DEACTIVATION);

m_dynamicsWorld->addRigidBody(body);


startTransform.setOrigin(SCALING*btVector3( btScalar(0), btScalar(20), btScalar(0) ));

body->getMotionState()->setWorldTransform(startTransform);


Comma before "but"


Do I need a comma before "but"?



I like your car but it seems to me too expensive for you.



Or



I like your car, but it seems to me too expensive for you.



My native languages are Ukrainian and Russian. In these languages this comma is required.




Answer



Either is ok. Commas indicate a pause. If you want to emphasize the contrast between the two clauses more, add the comma.


By the way you don't need the "to me" in that sentence; it's implied by the fact that the sentence is written in the first person ("I" is the subject).



I like your car, but it seems too expensive for you.



Advice from the BBC:



A comma (,) generally indicates pauses in speech. But, when it joins two clauses, it indicates a contrast between two ideas. In speech it is normal to draw attention to this contrast by a slight pause. A comma is the usual way of indicating this, although it is not obligatory:




Sheila can eat anything and large quantities of it, but she never puts on weight.


I'm going to make some New Year resolutions, but I don't suppose I'll keep them




Tuesday, February 26, 2019

procedural - Generating terrain using Marching Cubes


I searched around the web but I found nothing that could help me, so I'm asking here.



I'm trying to procedurally generate terrain using the marching cubes algorithm, and I can generate a mesh. The problem is that the mesh that may be anything!


https://www.dropbox.com/s/w99lvynrfra2a5v/question.JPG


As you can see in that screenshot, everything is messed up.


Is this a problem with the noise function? I'm using a simple Perlin noise function. How can I achive a result like this:


http://www.youtube.com/watch?v=-hJkrr5Slv8


If the problem is with the noise, what do I need to change to achieve this? I want to create natural terrain with hills, mountains, plains etc.


(I'm using Unity3D, but I don't think this makes any difference.)



Answer



I suggest scaling down the vertical component of the sample point before sampling the noise function.


The starting point of the voxel terrain in the video looks like a heightmap, so they may have multiplied the component by 0.



Also, you have to add the vertical component to the field function.


so your field function should look something like this:


const float noise_vertical_scale = 0.2;
const float field_vertical_scale = 0.01;
const float iso_surface = 0.5;

/*
* returns field at point (pos):
* negative = inside
* 0 = surface

* positive = outside
*/
float sampleField(vector3 pos)
{
vector3 sample_pos = pos;
sample_pos.y *= scale;
return noise3D(sample_pos) + pos.y * field_height_scale - iso_surface;
}

Hope that helps.



modal verbs - "Would", being the short version of "would like to" here?



Would can be used to describe what people are willing to do. This can also be seen as including an unspoken condition.



Tony would lend you his car. (... if you asked him ...)


Only a real fan would pay that much for a ticket (Only if someone was a fan would they pay ...)


--Page 78 (Macmillan - Inside Out English Grammar in Context Advanced)



Is this particular usage of "would" normal to see or hear?


Can I think of "would" here as being the short version of "would like to"?



Answer



It is not an elliptical or shortened version of would like to. It is rather a different, older sense of will meaning be willing to.


The modal auxiliary verb will developed from an Old English lexical verb which meant approximately want, desire. Today the modal has three distinct senses:





  • futurive, signifying future time reference



    Tomorrow John will go to London.
    John said yesterday that he would finish the job when he finds time.





  • dynamic, signifying persistent action




    When I was a child I would often read for hours every day.
    If you will keep teasing her you must expect her to get angry. (In this use, where it means approximately "If you insist on teasing her", will is strongly stressed.)





  • volitive, signifying willingness



    If they would only listen they might learn something.
    If you will bring beer, I will bring chips.






The dynamic and volitive uses may include future reference.


Software for learning pronunciation?


Is there some kind of program/app like Duolingo for learning pronunciation of the English language?


With consistent use of English as a written medium, you cannot not get better (in most cases), but how to improve pronunciation without studying/reading phonetic notation?




legal - How do I protect my rights to my game on the web?


My small games all have different gameplay. I want to showcase them through the internet. However, I'm worried about them and their concepts getting copied. How can I protect them?


Also, if I have to openly display the code to the open source community, how can I make sure I get credit for my work.




Monday, February 25, 2019

pronunciation - /kɑlm/ vs /kɑːm/


. . . calm . . .calm . . . [audio source]


• (UK) IPA: /kɑːm/, X-SAMPA: /kA:m/ • (US) IPA: /kɑm/, /kɑlm/, X-SAMPA: /kAhm/, /kAlm/ [wiktionary.org]


The first calm seems to be [kɑlm], and the latter [kɑːm]. Do I hear right or both sound [kɑlm]?



Answer



This article has an extended list of words with silent and pronounced "l".



For a language learner, the simplest rule is remembering some most commonly used words that do have silent "l":



  • -alk: talk, walk, chalk;

  • -ould: could, should, would;

  • -alf: half;

  • -alm: calm, palm;


Pronouncing the rest of the words with "l" articulated is not necessarily grammatical, but certainly more accepted/understood by native speakers.


Also, see this question on ELU for more details.


Update: as @tchrist noticed, words with -alm may be subject of variations.



phrase request - "Thank you in advance" - how to replace?


When writing emails, I often ended it with "thank you in advance". Even more, I used to have it in my signature for a certain time (mea culpa).

However, recently I've been told that it is not appropriate or even rude.


I checked on the Web and found some links (1), (2) that confirm this point.


There's also a discussion at ELU on this matter.


Instead of "thank you in advance", they usually suggest something like "I appreciate any help that you can provide" or "I will be grateful if you can..."


OTOH, in my native language there are two distinct types of appreciation: appreciation "after" is merely like English "thank you", but appreciation "before" can be translated something like "let the divine providence be with you" or "...give you power (to do what I'm asking)", or, simply speaking (not very accurate, though), "bless you (to do what I'm asking)".


I'm trying to combine both things, i.e. avoid using "thank you in advance" and preserve the meaning of above. Is it possible?


Thank you in advance! :-)



Answer



It might be better to just say, "Thank you." and omit "in advance." I think this implies that you are grateful that they took their time to consider your request. It would probably be a good idea to thank them again afterward, this time for whatever work they did to help you.


Unfortunately, some people (many of whom are very outspoken) will be offended by almost anything.



Usually, the best practice is to use the conventions that are generally accepted among whichever group of people you are communicating with.


plural forms - Is pronoun it really singular? Google transla


results of Google translator


Hi, I've used Google translator to translate a bunch of positive and negative sentences from Ukrainian, where the subjects of the clauses are plural. And I am really confused about, is it singular only? Or can we use it with plural objects? For me personally, when I speak English it is so inconvenient to say "these are not my problems" I usually say "it's not my problems" but then I think that I said it incorrectly. So why Google translator gave different results like


"this is my glasses"


vs


"these my glasses"


Thanks in advance.



Answer



"It" is singular. The plural third person pronoun is "they".




It's not my problem


They're not my problems.



In some cases you can get correct sentences in the form "singular is plural" For example "The problem is my friends". It is a little awkward, but grammatically correct. You might think of "my friends" to be short for "the group of friends" (and "group" is grammatically singular). So you can have:



What is the problem?
It's my friends; they want me to go out with them, but I need to study.



Nevertheless, normally we would use "they are my friends" "they are my scissors" "they are my glasses" "they are my problems".



Sunday, February 24, 2019

monetization - What are some common ways to generate revenue from a free game?


When creating a free game what revenue options are there and how successful are they? What are the pros and cons of different revenue models such as ad-supported, freemium, partnerships, merchandising, virtual goods, etc.?


If possible, give specific examples of games using different revenue models and provide data as evidence (otherwise it could get quite subjective).




Answer



Monetization heavily depends on the platform, but for the iPhone specifically, freemium (specifically, buying into something that lets you play more effectively) has proven itself to be probably the most viable strategy for games in which it fits.


A few sample points:



  • http://gamesfromwithin.com/the-power-of-free - a blog post talking about revenue in a freemium app, with increased sales even after making the game non-free

  • ng:moco has switched all their future games to be freemium, and their shooter Eliminate showed up in the top 100 revenue generating apps despite being free.


Of course, in the iPhone marketplace, monetization of microtransactions is fairly easy since it's all handled through iTunes and most users already have a credit card tied to their iTunes account. I'm sure you'll see similar stories coming from Facebook once there's a unified way of purchasing things on there instead of a bunch of different mechanisms.


As far as ad-supported, there are conflicting reports on that matter.


Here's one that says ads are good: http://www.macrumors.com/2009/05/06/adwhirl-free-ad-supported-iphone-apps-can-very-lucrative/



And here's one that says ads aren't worth it: http://www.macrumors.com/2009/02/20/appstore-secrets-price-drops-usage-and-ad-supported-models/


Of course both of those are before iAd came out.


syntax - Can I omit the second “is” in “is… and is…”?


What is the correct syntax:



This column is a primary key and null.




or



This column is a primary key and is null.



Should I write is again?



Answer



I would select 'is null' for both English and SQL reasons.


The alternatives are different in nature. I.e., primary key is singular ('a' primary key), but the null attribute is a mass noun. Having 'is' in front of both alternatives helps to highlight this difference.


Additionally, in SQL the syntax used to query a null column is (eg:)



WHERE column_value *IS NULL*

Because of this construct in the language, it will help to identify that you mean 'null' in an SQL sense (ie, has no data) and not necessarily in an English sense - which could mean invalid or wrong.


Saturday, February 23, 2019

Spatial data visualization level of detail


I have a 3D point cloud data set with different attributes that I visualize as points so far, and I want to have LOD based on distance from the set. I want to be able to have a generalized view from far away with fewer and larger points, and as I zoom in I want a more points correctly spaced out appearing automatically.


Kind of like this video below, behavior wise: http://vimeo.com/61148577


I thought one solution would be to use an adaptive octree, but I'm not sure if that is a good solution. I've been looking into hierarchical clustering with seamless transitions, but I'm not sure which solution I should go with that fits my goal.


Any ideas, tips on where to start? Or some specific method?


Thanks




should there be a definite article before "eye level"? (a quote from Salinger)


From Salinger's Zooey:



There were scars much nearer to eye level, too, from a rather awesome variety of airborne objects—beanbags, baseballs, marbles, skate keys, soap erasers, and even, on one well-marked occasion in the early nineteen-thirties, a flying headless porcelain doll.



I'm curious why there's no definite article before "eye level". Is level treated as a mass noun here? Could we add the before "eye level" without affecting the meaning?



Answer



As Jim states in a comment, "eye level" is a rough approximation rather than a specific measurement, in the same way that "room temperature", "ice cold", or "knee high" are. (And yes, I'm aware that the first two can have defined specifics, but in general use they are approximate.)



Wikipedia has a listing of the average height for a number of countries. A quick approximation from this list puts average human height (very) roughly around 155-158 cm. Thus, you could rewrite the start of the sentence like this:



There were scars closer to 157 cm high as well...



You certainly wouldn't add a definite article before "157 cm", would you? So the answer to your immediate question is "no, do not use a definite article in that context."


You could, however, write a sentence like this:



The insect flew past, inches from his face, and precisely at the level of his eyes.


...precisely at his eye level.




Note that this moves the context from a generic approximation of human height to a specific instance of one person's height. Instead of being an approximate placement of objects in an undefined area, it's a highly specific location relative to the person in question. (Even if we don't know how far off the ground his eyes are located, we know they must be some distance away from the ground.)


Your broader remark about level as a mass noun is a reasonable attempt to intepret the word, but incorrect. In standard English, there is no common usage that approximates to "[number] [units] of level". It is always used as a count noun:



The house has three levels plus a garage.


That is wrong on so many levels.


I completed the last levels of the game!



There may be some technical field that uses level as a mass noun, but again, it is not standard English usage.


Friday, February 22, 2019

sentence construction - had better to get or had better get


The sentence is


Travellers ________________ their reservation well in advance if they want to fly during winter vacation.


Which is suitable to complete this sentence. Please give some explanation so that I can understand.


1. had better to get


2. had better get



Answer




Had better is a construction called "modal idiom" by Quirk et al. It works like a modal verb, but not exactly.


It works like a modal verb in that it is followed by an infinitive without the particle to:



Travellers had better get their reservation well in advance if they want to fly during winter vacation.



You can substitute it with some other modal verb, it will also not require the use of to



Travellers will get their reservation... (modal verb will: no need to use the particle to)
Travellers must get their reservation... (modal verb must: no need to use the particle to)




There is another modal idiom that works like "had better": "would rather" -



Travellers would rather get their reservation well in advance than wait until the last moment. (see, it uses no to too)



There are two modal idioms that use to: "have got to" and "be to" -



Travellers have got to get their reservation well in advance, or they might loose their chance to fly.
Travellers are to get their reservation well in advance under a new law.



The meanings of these idioms are slightly different but what's important for your question is that only two of them use the particle to.





Reference: Quirk et al., A Comprehensive Grammar of the English Language, Topic 3.45, "Modal Idioms", page 141


verbs - Use of "go" in passive form


Can we use verb "Go" in passive voice?




Isn't the word "experience" wrongly used in this context?



Friend: Have you ever flirted with a female cop?


Me: Nope.


Friend: I have done that experience.



I think experience is the wrong word here. What else should he have said?




Answer



Experience is fine. The problem is the done. You don't do an experience1. You have an experience.



I have had that experience.



That's what he should have said. Or, alternatively, just relied on do alone:



Yes, I have done that.



Or, indeed, just use the have:




Yes, I have.



While there's other options, there was nothing wrong with using experience. The only problem is that you don't do experiences.




1: Well, there is a use of experience that has emerged in recent years that you would use to do to talk about, but it's not actually relevant here.


plural forms - Should I use hippopotami?


When should I replace an 'us' with an 'i'?


Are the following words valid?


Hippopotami (plural of hippopotamus)


Virii (plural of virus)


Bonii (plural of bonus)


When should I use 'i' and when should I just add es? Where does the i come from? And, when should I use 2 i's and when should I use just one? Thanks.




Thursday, February 21, 2019

negation - There is[n't] nowhere I'd rather be than here with you





A. There isn't nowhere I'd rather be than here with you.


B. There is nowhere I'd rather be than here with you.



Elsewhere I have read that two negatives in English destroy one another, although they are not always equivalent to an affirmative.


I'm not sure precisely what this means. So my questions are:



  1. What is the difference between A and B?

  2. Is A "standard" or acceptable English?





Why does editing the client's memory in some MMOs allow them to cheat?


Why editing the memory of the game client works? Why so many "Hack protection" tools coming with the clients?


If I were to design a client-server game, everything would happen at the server (the simulation of the game world) and clients would be only passive consumers receiving status updates of the part of the world near their characters, sending only some information like keystrokes or move/action commands. Maybe I missing something here, but with that design, any hack like raising my STR by 200 in the client memory (if the value is present at all), just won't have any effect.


The only explanation I can think is that games in which memory editing works let parts of the simulation run in the client and the server then just synchronize all the clients periodically. I can understand that design for Real Time Strategy games with a fixed number of players once a match is configured, but, why in MMORPGs? Is it a strategy to reduce server load?



Answer



While ideal, it is practically improbable to validate every single input against the server, both in terms of computational load and latency in input confirmation for the client.


Consequently there are usually a handful of things that aren't validated on the server in many MMOs. In some cases this includes certain classes of character movement, which is why teleportation and speed hacks exist. Client-side protections help provide an extra barrier to those hacks, although of course with sufficient time they can be bypassed. To combat this, many such games would employ a strategy of logging and after-the-fact verification and rotation of the actual protections employed.


There's also the issue of screen other simple memory-scraping hacks that can collate information and transmit keypress and other input back through the client faster than a human can normally react. Or they can look for information that may be transmitted to the client but not necessarily visible yet (such as the positions of creatures that are close by but not displayed anywhere yet, as was common in early Diablo map hacks).


legal - Unity remove logo in splash screen


Heavily related to this question, as of now, Unity's TOS has changed dramatically. And searching in the TOS, it looks like I'm allowed to remove the Unity logo in my exported game. Looking at Section 4.1, it still retains:



You will not remove, alter or obscure any copyright, trademark, service mark or other proprietary rights notices incorporated in or accompanying the Services.




However looking at how "Services" is defined in the first paragraph of the TOS:



Unity Technologies ApS (“Unity”, “our” or “we”) provides game-development and related software (the “Software”), development-related services (like Unity Analytics (“Developer Services”)), and various Unity communities (like Unity Answers and and the Made with Unity Platform (“Communities”)), provided through or in connection with our website, accessible at unity3d.com or unity.com (collectively, the “Site”). Except to the extent you and Unity have executed a separate agreement, these terms and conditions exclusively govern your access to and use of the Software, Developer Services, Communities and Site (collectively, the “Services”)



It does not seem to include the exported game itself. And even if Section 4.1 says "accompanying the services", I assume it still wouldn't include the game as the game does not need to accompany them. Otherwise it would be illegal to remove the logo from the splash screen from a game made in Unity Pro since the TOS applies to all tiers of Unity. Furthermore, I haven't found anywhere that says you can't modify or hack into the produced executables (I even looked in here which contains another part of the TOS). Does this mean I can remove the logo from the splash screen no matter what Unity tier (personal, plus or pro) I'm using?


(My aim is to actually move it to a dedicated credits section accessible from the title screen of the game rather than having it appear in the splash screen. Players of the game will still know that it's made in Unity.)



Answer




  1. The exported game still includes the Unity engine Software.


  2. Unity are the ones that should be contacted with request for clarifications and executing a separate agreement that would let you move the logo.

  3. Consult a lawyer.


2d - Identifying quad patterns in a two-dimensional array


In the tech demo I'm trying to make, tetrominoe-style blocks will be placed by the player, at which point the game checks to see if they've made a quad with any existing shapes on the board (a 2D array). If so, the quad should be processed in some way.


I have a 2D array like so:


[ [0, 0, 0, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 1, 1],
[1, 0, 0, 1, 0, 1] ]


And I need to identify 'quad' patterns such as that in the top-right corner, e.g.


[ [1, 1, 1],
[1, 1, 1],
[1, 1, 1] ]

I'm not sure of the best way to do this. I've had a look at some two-dimensional array pattern matching algorithms, which all seem to flatten the 2D array into 1D, then use a 1D text searching algorithm (e.g. KMP) to identify any matches. My problems with that idea are that the quad can be any size, as long as it's rectangular and bigger than an arbitrary minimum (in my case, 2 x 2).


I also thought about using some variant of the 4 way flood fill algorithm or connected-component labelling, for each position of the newly-place tetrominoe. But I'm not quite sure how to best follow the path out and establish the bounds of a quad (for example, capturing this:


[ [1, 1, 1],
[1, 1, 1],

[1, 1, 1] ]

out of this:


[ [1, 1, 1, 1],
[1, 1, 1, 0],
[1, 1, 1, 0] ]

My latest though is perhaps a floodfill to get all interconnected parts after a tetrominoe lands, then 'round off' the jagged edges, maybe by checking the number of neighbours of each block, if it's 1, remove it, repeating the process until all remaining blocks have 2 or more neighbours. But this seems like it could be slow.


Has anyone any experience of this problem, or any pointers about how best to accomplish this task? I'm sure there's a common or at least applicable algorithm, I just don't know it!



Answer




I drew it.


some scenarios considering only square-shaped quads




  • Coloured backgrounds are the layout of filled squares just after a block has been placed.

  • Red circles are locations that could potentially be the top-left corner of a quad.

  • Red lines are on squares around a potential corner that must be filled for the shape to be a quad.

  • Red crosses are locations that were checked and found to be empty. (In the last two diagrams, I've connected them to the red circle from which the check was made.)




In the first diagram (green), things worked out fantastically. The very first top-left corner we checked has filled squares on its bottom-right outline that form a 2x2 block. If we try to be even more ambitious and form a 3x3 block, we find that some of those (the red crosses) are not filled. So all we got is a 2x2.


In the second diagram (blue), things worked out easily also. Except this time, even the second bottom-right outline matched on all squares: We have a 3x3 block. Trying for a 4x4 fails, as not all squares are filled.


In the third diagram (purple), we've got nothing. We ran out of filled squares to place the corner in before we found one that has a bottom-right outline.


In the fourth diagram (yellow), things worked after some trying. The first three squares we tried to place corners in had no bottom-right outline. The fourth, however, did. This gives us a 2x2. Trying to get a 3x3 fails as in the first diagram.



If your corner is grid[0][0], the nth bottom-right outline consists of squares where one or both coordinates are n.


nth bottom-right outlines up to 3


This generalises to: If your corner is at grid[x][y], then the bottom-right outline is a union of these sets of squares:



  • grid[x+n][yVariable], where y <= yVariable < y+n (the right side)


  • grid[xVariable][y+n], where x <= xVariable < x+n (the bottom side)

  • and finally grid[x+n][y+n] (the bottom-right corner)


It should be easy to iterate through these. If you have a quad, the top-right and bottom-right corners' coordinates tell you where it is.


That only works for squares though!



Those three bullet points above can also be checked for individually:


separate checking of sides


This of course means that from any state of checking, 3 (instead of 1) possible further states may evolve:


the three checking states that follow from a the trivial state



Each of these three states can each be further expanded into up to three states by a similar method.


Your code could save the two other states for later and process the first to exhaustion before continuing with the next. At the end, the quad with the largest area would be the output. (This is, in computer science terms, a depth-first traversal of a trinary tree.)


c++ - What do I need to implement a side-scrolling screen, like in classic platformer games?


I'm working on a game in Allegro for C++. I'm stumped about how to scroll the screen.


I'm trying to make the screen scroll with the player, as it does in classic side-scroller games such as Super Mario Brothers. What is the approach I should take to implement such behavior?




Wednesday, February 20, 2019

plural forms - All of them are wearing an orange shirt. OR All of them are wearing orange shirts


Let's say there're three boys, and they all are in an orange shirt. Then, which one is correct?


A. All of them are wearing an orange shirt.


B. All of them are wearing orange shirts.



Of course, each of them is wearing ONE orange shirt, but because all of them are in a orange shirt, there're three orange shirts. So I'm confused.



Answer



Here is an example of single v.s. plural:


All of them are wearing orange shirts.


v.s.


Each of them is wearing an orange shirt.


This is because the first sentence refers to multiple shirts (on multiple people) and the second sentence refers to the single shirt worn by each member of a group of people.


phrasal verbs - Turn Equipment On



I have a question about the pattern "turn on " here:



Then he allegedly turned the body-building equipment on his 44 year-old wife, identified by sources as Feng Liang, and his elderly mother-in-law, Feng Kun Zaehng,77, the sources said.



I understand the phrase "*turn the gun on ", am not sure about "turn the equipment on ". Could the example be wrong?




plural forms - Could it be a structure of "How many -singular noun- is there?"


We had an argument in our collage if it's possible to have such structure:



"How many -singular noun- is there?"



For example:




How many chair is there?



The claim of the supporters: This structure should be used in case that t is not known whether there is one one or more chairs there. While just in case that it is known certainty that there are more than one chair, it should be "how many chairs are there".


The claim of the opponents: This structure cannot be since using the phrase "how many" always should be with a plural noun.


Both sides are not native English speakers, then I would like to know what is the truth.




Water/Ocean simulation and physics


I'm looking for some references about water simulation, and how to model it's interaction with bodies (like boats, ships, submarines).


I've found a lot of references on the visual aspects of water (waves, reflection, etc), but very little about how to deal with the way it should interact with bodies. My experience with game development is very limited, and I'm really stuck here.


Bascally I would like to be able to make the position of a ship variates according to the waves. How can I do this?


I'm using Panda3D, but hope to hear about techniques and implementations used in any available technology.




Answer



Basically you're looking at modeling 6 things for a ship: pitch, yaw, roll, heave, sway and surge.


alt text


Pitch, yaw and roll are rotations the ship can make as it twists and turns going up and down the slope of the waves. Heave, sway and surge are movements induced by the waves pushing the ship around and/or the ship sliding down the face of a wave.


"Like a Car Driving on Hills..."


Imagine a boat on the water like a car driving over hilly ground. If the car drives over rolling hills (like a ship going over waves) it is going to tilt and angle as it goes up and down the hills. This is the pitch, yaw and roll. If the hills (waves) are big, the car (ship) will drive up and down, pitching, yawing and rolling as it goes. If the hills (waves) are really small (smaller than the car/ship), then the car (ship) is just going to drive over them and not pitch, yaw or roll much.


A big ship can just plow through smaller waves, whereas a small ship will move up and down the waves. Taking our car example, imagine someone riding a bicycle (small ship) over a set of small hills (waves). They will roll up and down as they go. Then someone drives a big truck (ship) over them. The truck is bigger than the hills, so doesn't really pitch up and down as it goes over them.


Unlike the car though, a ship is part way into the water, so it's movements are going to be dampened somewhat. Imagine a car with really soft spongey tires. When it drives over tiny hills, the spongey tires just smooth it out. A ship's movements are also dampened, so little waves won't make it bounce up and down like a car on a rocky road. A submarine is sort of the ultimate dampened ship, as when submerged it is pretty much immune to the surface waves. But if it's on the surface it's going to be moved by the waves.


A ship will also slide on waves. A ship going down the face of a wave will surge forward for example. So to extend our car example, make it a car with big spongey wheels driving on a somewhat slippery surface. Unless the car is running the engine to compensate for the slip, it's going to slide down the side of a hill. Even if it is running the engine, there is going to be some slip.


The one place where the car and hill analogy has problems is the fact that the waves change shape over time. A stationary ship will bob up and down as the waves go up and down.



Waves Moving the Ship


If there is no wind blowing on the ship to move it along, and the waves are a perfect sine wave shape, then the ship basically won't move anywhere as it bobs in the waves. It slides one way as it goes up the face of a wave, then slides back the other way as it goes down the back face of a wave.


However if the waves are NOT symetrical (like the picture below), then the waves are going to move the ship. Because one side of the wave is steep, the ship is going to slide quickly down that face as well as be pushed by the face of the wave. The gentle back slope of the wave however won't have much motion.


alt text


This isn't the most perfect model of wave motion and shape affecting a ship's motion, but it will probably do for a rough simulation.


Wind Effects


Wind is also going to push your ship around in ways independent of the wave motion or ship motion. The direction and force of the wind can be different than the direction and force of the waves.


Buoyancy


Buoyancy is how well your ship floats. Very buoyant ships float up high in the water, and ones that aren't buoyant sink. Neutrally buoyant ships (submarines) can basically "hover" at any point underwater, neither sinking nor rising. If you want to simulate a ship sinking, make it become negatively buoyant and it will begin to sink.


Buoyancy also affects dampening of the ship's motion. A ship that is extremely buoyant will bob around on the water surface and be strongly affected by waves. A ship that is less buoyant will be partially submerged and not be affected as much. Think of the difference between a pingpong ball floating on the surface versus an apple, which floats but is partially underwater. The pingpong ball bobs up and down with every wave motion. The apple on the other hand doesn't respond to every wave detail.



Capsizing


If the pitch, yaw and/or roll exceed some value, your ship is going to tip over. When it tips over, it might fill with water, reducing the buoyancy, thus making it not float any more.


Getting Sea Sick :o~


A ship that is traveling parallel to the direction of wave motion is "in the trough", and will produce the most nauseating effects at least in my experience :) If you are traveling in the direction the waves are going, you can have a very smooth ride - like having the wind at your back. If you are traveling in the opposite direction as the waves, you will have a pretty harsh ride as you are hitting each wave "hill" as it comes at you. Makes for a pretty exciting ride though!


Further Reading


Here are three articles that cover the science behind this, which might give you some insights. Though heavy on the math and science, they could give you an idea of what the different factors are.


Article 1: Modeling of Ship Roll Dynamics and Its Coupling with Heave and Pitch


Article 2: Modelling and Simulation of Marine Surface Vessel Dynamics


Article 3: Modelling and Simulation of Marine Surface Vessel Dynamics


The Author Doing Field Research



Here's me about 15 20 years ago when I worked on research ships :)


alt text


meaning - What does "I have straight A's." mean?


In this video of Hillary Clinton, at 15s, the child said "I have straight A's.".


What does "straight A's" mean?



Answer



In the U.S., examinations are traditionally graded by letter of the alphabet, commonly A-F, with A being the highest pass grade.


A 'Straight A' student is one that has achieved an A Grade across all subjects taken


"Like" as nonstandard adverb and informal interjection for the approximation: function or meaning?


Two examples from Dictionary.com for like:




(1) I did it like wrong. [Adverb. Nonstandard. a) as it were; in a way; somehow]
(2) Like, why didn't you write to me? [Interjection. Informal. (...to preface a sentence, to fill a pause, to express uncertainty, or to intensify or neutralize a following adjective)]




(1a) I did it, like, wrong.
(2a) Hey, why didn't you write to me?



Collins possibly shows (1) and (2) as instances of the same thing, but labelled differently depending on AmE/BrE. The AmHDotEL shows be like as an idiom for to say/utter, and has an intriguing usage note saying : "If a woman says "I'm like, 'Get lost buddy!'" she may or may not have used those actual words to tell the offending man off. In fact, she may not have said anything to him[...]".



  • Could you have (1a) as an instance of (2) i.e. the person hesitates and pauses but just means plain wrong and not wrong somehow?

  • In what way is (1) Nonstandard as opposed to informal; could you say something like (1) at work for instance? Does that mean used by younger people?


  • In (2), what other word or phrase would mean the same thing or play the same role as like here? Is this about emphasis, hesitation, are you saying "in a roundabout way", is that to "be like", or are you asking the person to themselves summarize why they did or didn't do something; or is it really just like (2a)?



Answer



Important things first! None of these are appropriate for use at work!


As for use by younger people -- sort of, they came to prominence in 'hippie' culture of 1960's among younger people -- but of course some of us are not 'younger' any more.


If (1) is written down, rather than spoken, I would always expect it to be as in (1a), placed between commas. I would only expect to see it as dialog; i.e., representing the spoken words of a 1960's or 70's hippie or someone similar.


In my experience, (Canada, Toronto, 1970's) the function is to apply some extra emphasis to the following word or phrase. It acts as a pause for dramatic effect. So, in (1a) it implies that the speaker did something so obviously wrong that he must have been really drugged or drunk (for example) or just very foolish. But it also tends to get over-used such that it serves no more than the function of 'um,' or 'uh,' creating an artificial pause while the speaker thinks of what they mean to say next.


In (2) I believe it does serve the same function as 'Hey' in (2a) but I would find the shade of meaning slightly different


Hey, why didn't you write me? -- sounds more accusing


Like, why didn't you write me? -- sounds as if you probably forgot



Umm, why didn't you write me? -- sounds like there might be some sneaky hidden agenda


The other usage mentioned 'I'm like, "get lost buddy"' in my recollection appeared later .. or perhaps I encountered it only upon moving to California in late 1980's and it did generally mean 'I was thinking/feeling (strongly)...'


Also not for use 'at work'.


What is the difference between "gerund" and "infinitive"?


What is the difference between "gerund" and "infinitive"? I do not understand the differences.Can you explain them?



Answer



Taken from Gerunds and Pronouns on this blog:




Gerunds and Verbal Nouns: Because they are noun-like, we can think of gerunds as names. But rather than naming persons, places, things, events, and the like, as nouns generally do, gerunds, because they are verbs in form, name activities or behaviors or states of mind or states of being.


A gerund is derived from a verb by adding the suffix -ing. The result is still a verb, and it exhibits ordinary verbal properties, such as taking objects and adverbs.



Example: In football, deliberately tripping an opponent is a foul.



Here the verb trip occurs in its gerund form tripping, but this tripping is still a verb: it takes the adverb deliberately and the object an opponent. However, the entire phrase deliberately tripping an opponent, because of the gerund within it, now functions as a noun phrase, in this case as the subject of the sentence. So, a gerund is still a verb, but the phrase built around it is nominal, not verbal.


Infinitive phrase : An infinitive phrase is the infinitive form of a verb plus any complements and modifiers. The complement of an infinitive verb will often be its direct object, and the modifier will often be an adverb.



Example : He likes to knead the dough slowly.




The infinitive verb is to knead. The complement is its direct object (the dough). The modifier is the adverb (slowly).



More examples of Infinitive Phrases:



He helped to build the roof.
The officer returned to help the inspectors.
She tells you to dance like no one is watching.



Tuesday, February 19, 2019

c++ - OpenGL Strange mesh when animating Assimp


I'm trying to animate a skeletal mesh. The mesh loads with no problems and all is set up correctly. My problem is that when I calculate the matrix for a given keyframe the mesh go nuts.


Here is na image of the problem.


enter image description here


The mesh on the right is using the boné transform as the final matrix. the ne one the left is using the matrix calculated from keyframes. I don't know where i'm going wrong with this.


Here is my code:



The Animation Clip where all keyframes are stored:


Matrix4 AnimationClip::GetTransform(Bone *bone, float deltaTime)
{
Channel* channel = channels[bone->name];
if (channel == nullptr)
return bone->transform;
else
return channel->Update(deltaTime);
}


///////////

Channel::Channel(aiNodeAnim* animNode)
{
name = string(animNode->mNodeName.data);

for (GLuint k = 0; k < animNode->mNumPositionKeys; k++)
{
aiVectorKey vec = animNode->mPositionKeys[k];
positions.push_back(

Keyframe(
(float)vec.mTime,
Vector3(vec.mValue.x, vec.mValue.y, vec.mValue.z)));
}

for (GLuint k = 0; k < animNode->mNumScalingKeys; k++)
{
aiVectorKey vec = animNode->mScalingKeys[k];
scalings.push_back(
Keyframe(

(float)vec.mTime,
Vector3(vec.mValue.x, vec.mValue.y, vec.mValue.z)));
}

for (GLuint k = 0; k < animNode->mNumRotationKeys; k++)
{
aiQuatKey vec = animNode->mRotationKeys[k];
rotations.push_back(
Keyframe(
(float)vec.mTime,

Quaternion(
vec.mValue.x,
vec.mValue.y,
vec.mValue.z,
vec.mValue.w)));
}
}

Matrix4 Channel::Update(float animTime)
{

return
CalculatePosition(animTime) *
CalculateRotation(animTime) *
CalculateScaling(animTime);
}

Matrix4 Channel::CalculatePosition(float animationTime)
{
return
Matrix4::CreateTranslation(

CalcInterpolatedPosition(animationTime));
}

Vector3 Channel::CalcInterpolatedPosition(float animationTime)
{
if (positions.size() == 1)
return positions[0].value;

GLuint positionIndex = FindPosition(animationTime);
GLuint nextPositionIndex = (positionIndex + 1);


float deltaTime =
positions[nextPositionIndex].time - positions[positionIndex].time;
float factor =
(animationTime - (float)positions[positionIndex].time) / deltaTime;

Vector3 startPos = positions[positionIndex].value;
Vector3 endPos = positions[nextPositionIndex].value;

Vector3 delta = endPos - startPos;


return startPos + delta * factor;//Vector3::Lerp(startPos, endPos, factor);
}

GLuint Channel::FindPosition(float AnimationTime)
{
for (GLuint i = 0; i < positions.size() - 1; i++) {
if (AnimationTime < (float)positions[i + 1].time)
return i;
}

return 0;
}

And Here is my Skinned Mesh code where I'm fetching the keyframes:


void SkinnedMesh::BoneTransform(
double delta,
vector& transforms,
AnimationClip *anim)
{
Matrix4 identity_matrix = Matrix4::Identity();


float ticksPerSecond =
anim->ticksPerSecond == 0 ? 25.0f : anim->ticksPerSecond;

double time_in_ticks = delta * ticksPerSecond;
float animation_time =
fmod((float)time_in_ticks, anim->duration);

UpdateTransforms(
animation_time,

anim,
rootBone,
identity_matrix);

transforms.resize(m_num_bones);

for (GLuint i = 0; i < m_num_bones; i++)
transforms[i] =
m_bone_matrices[i].final_world_transform;
}


void SkinnedMesh::UpdateTransforms(
float p_animation_time,
AnimationClip *anim,
Bone *parentBone,
Matrix4& parentTransform)
{
Matrix4 boneTransform =// parentBone->transform;
anim->GetTransform(parentBone, p_animation_time);


Matrix4 global_transform =
parentTransform * boneTransform;

if (m_bone_mapping.find(parentBone->name) !=
m_bone_mapping.end()) // true if node_name exist in bone_mapping
{
GLuint bone_index = m_bone_mapping[parentBone->name];
m_bone_matrices[bone_index].final_world_transform =
m_global_inverse_transform *
global_transform *

m_bone_matrices[bone_index].offset_matrix;
}

for (vector::iterator it =
parentBone->children.begin();
it != parentBone->children.end();
it++) {
UpdateTransforms(
p_animation_time,
anim,

(*it),
global_transform);
}
}

void SkinnedMesh::Render(Shader* shader, AnimationClip *clip)
{
vector transforms;
BoneTransform(
(double)SDL_GetTicks() / 1000.0f,

transforms,
clip);

for (GLuint i = 0; i < transforms.size(); i++)
{
GLfloat values[16];
Matrix4::ValuePointer(transforms[i], values);

string a = "jointTransforms[";
a.append(to_string(i));

a.append("]");

glProgramUniformMatrix4fv(
shader->GetID(),
shader->GetUniformLocation(a.c_str()),
1,
GL_FALSE,
(const GLfloat*)values);
}


for (unsigned int i = 0; i < meshes.size(); i++)
meshes[i]->Render(shader);
}

It seems the matrices are all wrong and therefore deforming the mesh. Can you help me?


EDIT :


The Meh on the right has this code :


Matrix4 AnimationClip::GetTransform(Bone *bone, float deltaTime)
{
Channel* channel = channels[bone->name];

if (channel == nullptr)
return bone->transform;
else
return bone->transform;

}


EDIT 2 :


As daniel_1985 Pointed out my matrices might have to be transposed but I'm in doubt…


this is how I'm Converting Assimp matrices now


Matrix4 Matrix4::ToMatrix4(aiMatrix4x4 mat)

{
Matrix4 result;

result.row0 = Vector4(mat.a1, mat.b1, mat.c1, mat.d1);
result.row1 = Vector4(mat.a2, mat.b2, mat.c2, mat.d2);
result.row2 = Vector4(mat.a3, mat.b3, mat.c3, mat.d3);
result.row3 = Vector4(mat.a4, mat.b4, mat.c4, mat.d4);

return result;
}


this is the result If I set my skinned mesh to its bones transforms


enter image description here


So What am I doing wrong…..Is the matrix being correctly converted or not? Na if it is Why does my mesh get deformaed like this?


I am building my bone hierarchy like this :


void SkinnedMesh::BuildBoneHierarchy(
aiNode* node,
Bone* parentBone)
{
if (parentBone == nullptr)

{
rootBone = new Bone();
rootBone->name = string(node->mName.data);
rootBone->transform =
Matrix4::ToMatrix4(node->mTransformation);

for(GLuint i = 0; i < node->mNumChildren; i++)
BuildBoneHierarchy(
node->mChildren[i],
rootBone);

}
else
{
Bone* bone = new Bone();
bone->name = string(node->mName.data);
bone->transform =
Matrix4::ToMatrix4(node->mTransformation);
parentBone->children.push_back(bone);

for (GLuint i = 0; i < node->mNumChildren; i++)

BuildBoneHierarchy(
node->mChildren[i],
bone);
}
}

UPDATE :


So I've succesfully fixed my skinned mesh for its pose by calculating manually each bone inverse Transform…. Like this :


void Bone::CalcInverseBindTransform(Matrix4 parentBindTransform)
{

Matrix4 bindTransform = parentBindTransform * transform;
inverseTransform = Matrix4::Invert(bindTransform);

for (vector::iterator iter = children.begin();
iter != children.end();
iter++)
(*iter)->CalcInverseBindTransform(bindTransform);
}

In my Update Transforms I'm setting the mult like this:



GLuint bone_index = m_bone_mapping[parentBone->name];
m_bone_matrices[bone_index].final_world_transform =
m_global_inverse_transform *
global_transform *
parentBone->inverseTransform;

But the when I animate it, it goes nuts…. So… What do I need to do now?


enter image description here




collision detection - How do I calculate the angle of the slope at a point on a 2D bitmap terrain?


I have an arbitrary destructible bitmap terrain like the one in "Worms". It's easy to work out if a character or missile intersects the terrain, but how do I work out the angle of the slope at the contact point, so I can make grenades roll down hills, bounce off at the right angle, etc. I know it can be down by somehow taking a sample of points around the impact point and seeing which ones intersect, but I'm not sure exactly how to go about it, and in an efficient way.



Answer



If you're happy sampling then run a coarse sample at a defined radius around your hit point. 16 samples in a circle will provide you with quite accurate curvature. If you add up all the vectors that "missed", you'll have a vector that can be normalised to a surface normal.


If you hit the flat floor, all the vectors will miss if they're pointing up at all, so they add up to an up vector. If you hit a 45 degree slope, the vectors that point away from the slope will miss and add up to a 45 degree vector away from the slope. Even a rough surface will provide a reasonable surface normal as you're checking for "misses" not a surface.


This works fine until you get into really tight spaces, at which point, curvature is all shot to crap anyway, and you would probably not get a sensible result in any technique other than precomputed surface normals (which can be found by blurring a "vector to closest feature" map where feature is non colliding / non matter).


so:


Vec collisionPoint # point of collision
Vec acc(0,0)

for f = 0 to 2pi:
vec check = vec( sin( f ), cos( f ) )
if ( check + collisionPoint ).collides():
acc += check
normal = acc.normalise() # yes, there is a chance of a divide by zero.

Monday, February 18, 2019

Is there a word for "divulging unintentionally"?




The President * information to an unauthorized staff of the White House.



I am wondering if there's a word for divulging unintentionally like as in a person leaking corporate information to a person who's not supposed to have that information unintentionally. Is there such a word?



Answer



For a one word option, there's "blab" which means



to reveal a secret especially by indiscreet chatter




but it's not a particularly formal word--I wouldn't expect to read it in a news article.


I would expect to see something like "let slip."



He let privileged information slip to an unauthorized member...



If formality isn't an issue at all, there are also variations like "spill the beans."


xna - 360+ degree rotation skips back to 0 degrees when using Math.Atan2(y, x)


I'm new to XNA and this is my first actual project, so forgive my noobness.



I'm using


 jointAngle = System.Math.Atan2(RightStick.Y, RightStick.X);

in order to set an angle of a joint (farseer) so that the attached body points in the direction pushed with the right joystick. This all works great and i get values from negative pi to pi which correlate with the pushed direction. The problem arises when i go from 360 degrees to 361. Instead of the continued rotation beyond 360 degrees that one might expect, it jumps back to 0 degrees (or -3.14 radians), which causes a jerking motion as the joint suddenly shifts 359 degrees back instead of 1 forward.


Is there a simple way to account for this? I came up with a few solutions, but they're all pretty messy at best and completely unreliable at worst.


Please help!



Answer



atan2 is a mathematical function; it is stateless. There is nothing in it to “know” that you want an angle which is close to the angle from the previous frame, as opposed to an angle which is simply sufficient to identify the direction.


You must write your own logic to handle this case. There are several possible behaviors you could implement; here's the ones I've thought of. Note that I am not familiar with C#, XNA, or Farseer, so I have only pseudocode here, but all of these should work as long as you can retrieve the joint's current actual angle as well as the target angle.





  1. The joint should spin the smallest amount to match the direction of the joystick. This means that if the user spins the stick faster than the joint can keep up, it will start turning the other direction to make a shorter motion. This can be implemented as:


    let currentStickDirection = atan2(RightStick.Y, RightStick.X)
    let currentJointDirection = currentJointAngle mod 2π
    let difference = ((currentStickDirection - currentJointDirection + π) mod 2π) - π
    jointTargetAngle = currentJointAngle + difference

    The addition and subtraction of π (a half-turn) combined with modulus puts the difference-between-angles in the range −π…+π, which is the “smallest amount to match” property.


    Note that if you are implementing, for example, a turret, then this might be undesirable as it makes it harder to strafe a particular arc as the player needs to make sure not to lead too much.





  2. The joint should follow the motions of the stick. That is, if the user quickly makes multiple revolutions of the stick, the joint will follow and make multiple revolutions even if the user's movement is long over.


    To implement this, the logic is the same as above except that instead of using the joint's current actual angle, we use the joint's target angle (which can be simply a variable/field in your program, unrelated to the physics engine) as the state input.


    let currentStickDirection = atan2(RightStick.Y, RightStick.X)
    let currentJointDirection = jointTargetAngle mod 2π
    let difference = ((currentStickDirection - currentJointDirection + π) mod 2π) - π
    jointTargetAngle += difference


  3. Same as option 2, but the joint will never make an unnecessary full revolution. This differs from option 1 in that the joint will always turn in the same direction as the input does.



    To implement this, use the code from option 2, but after all of the above we also remove extra ±2πs from the target angle:


     let revolutions = (jointTargetAngle - currentJointAngle) / 2π
    if (revolutions >= 1)
    jointTargetAngle -= floor(revolutions) * 2π
    else if (revolutions <= -1)
    jointTargetAngle -= ceil(revolutions) * 2π




Note that if the stick is near its center, then small motions, possibly including noise/vibration rather than user motion, will cause large changes in the computed angle. If you haven't already, you will probably want to add a “dead zone” around the center which disables the angle computation. This can be a simple distance condition, like pow(RightStick.Y, 2) + pow(RightStick.X, 2) < pow(deadZoneRadius, 2).



Another interesting option would be to reduce the “motor power” of the joint (I don't know what exact options Farseer provides in this area) depending on the computed distance, so that small pushes on the stick can be used to slowly swing the joint (note that then the imprecision of direction matters less) and moving it to the limit does a fast swing. This would naturally reduce the effect of noise about the center, but unless you are using option 1 above (which does not depend on the previous target angle) and your joystick has perfect mechanical return-to-center, you will still want to have a deadzone.




Commentary: The two key principles here are:



  1. Work with differences between angles, not absolute angles.

  2. Make sure that (where appropriate for the application) you are treating any particular angle θ as equivalent to θ + 2π. This is the reason for all of the uses of modulo; the π offsets are used to control where we flip from positive to negative numbers, which affects the overall behavior of the algorithm, but not in a way which is dependent on the input range.


causative have - You MADE/HAD/GOT me check the dictionary


Earlier today, I read an answer by jonlink which used the zero plural aspirin. I wasn't sure whether that was correct, so I had to check a dictionary. I found that both aspirin and aspirins are okay as plural forms.


If I wanted to express this in a comment, which sentence would I use?



 1. You made me check the dictionary.
 2. You had me check the dictionary.



I think these first two sentences sound natural. I'm not sure about using the pronoun you, though; it might sound rude.




 3. You got me check the dictionary.



This last one doesn't sound right. Is there a problem with using got this way?



Answer



In this context, I would say all three sound unnatural - the answer didn't make you check the dictionary, it prompted you to.


Made would only be used if you're either joking (where the person clearly didn't force you to do anything) or where you've actually been forced to do something. Your example could fall into the former, but the setting isn't quite casual enough to and could potentially be seen as a criticism.


(Note that the above isn't a reflection on the StackExchange user mentioned in the initial post, or StackExchange in general, just that suggesting someone forced you to undertake an act should be done with care)


prepositions - I switched out the Orb "on" him



Peter Quill: He is gonna be so pissed when he realizes I switched out the Orb on him.


Gmora: He was gonna kill you, Peter.


Peter Quill: I know. But he was about the only family I had.


Gmora: No. He wasn't.


-- Guardians.of.the.Galaxy.2014



enter image description here



Although I fully understand what this dialogue is all about, I'm wondering what the usage of on is here.


I think on indicates who is the recipient of the action.


Can you please give me some more examples?



Answer



I played a trick on her.


I went Jackie Chan (or Chuck Norris) on him (also on his ass): I used martial arts on him.


My car died on me.


21. Informal. so as to disturb or affect adversely: My hair dryer broke on me.


http://dictionary.reference.com/browse/on


opengl - Zooming to point of interest


I have the following variables:



  • Point of interest which is the position(x,y) in pixels of the place to focus.

  • Screen width,height which are the dimensions of the window.

  • Zoom level which sets the zoom level of the camera.



And this is the code I have so far.


void Zoom(int pointOfInterestX,int pointOfInterstY,int screenWidth,
int screenHeight,int zoomLevel)
{
glScalef(1,1,1);
glTranslatef( (pointOfInterestX/2) - (screenWidth/2), (pointOfInterestY/2) - (screenHeight/2),0);

glScalef(zoomLevel,zoomLevel,1);
}


And I want to do zoom in/out but keep the point of interest in the middle of the screen. but so far all of my attempts have failed and I would like to ask for some help.



Answer



So you want zoom just like in google maps? If you hover over city and zoom there cursor stays top of that city. This give smooth transition.


        public static final void zoom(float amount, float toX, float toY) {
float oldZ = camera.zoom;
camera.zoom += amount;
// If zooming still has effect then we need translate map towards cursor
if (camera.zoom < minZoom) {
camera.zoom = minZoom;

} else if (camera.zoom > maxZoom) {
camera.zoom = maxZoom;
} else {
float a = (toX - (float) HALFSCREENSIZEX)
* (oldZ - camera.zoom);
float b = (-toY + (float) HALFSCREENSIZEY)
* (oldZ - camera.zoom);
camera.translate(a, b, 0);
//check boundaries if you have any.
}

}

To make this work with matrix stack you might have to peek there http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/graphics/OrthographicCamera.java


Zooming is just multiplier for viewport size there. I have done this with matrix stack too but its much cleaner to use camera class.


grammaticality - Are there tools or techniques to stop translating literally?


My girlfriend speaks English as her third language, but not yet fluently.


Her vocabulary is quite extensive, especially due to the fact that she reads a lot (fiction and non-fiction) and regularly watches movies and news channels in english.


The main problem she's facing is that she can't stop translating too literally from her mother tongue (namely Armenian). I've noticed at least three patterns that lead her to make mistakes:



  • Wrong use of prepositions. For example she often says "look on" for "look at".

  • Wrong use of verbs. For example she would use "enter" in lieu of "get in", "stop by", "visit", etc.


  • Wrong word order. E.g. putting the subject after the verb in a statement, failing to invert or use the auxiliary "do" in questions.


All the phrases that sound awkward (or plain ungrammatical) would make prefect sense in her mother tongue if translated back literally. Also, she knows she is making a mistake and no matter how many times I correct her, she can't help but make the same mistake again.


If she still manages to convey the meaning of her sentences when speaking, things worsen when she has to write something (say a report for her classes). In this latter case it's difficult to find a phrase that makes complete sense or at least that doesn't sound odd.


To come to the point, I'm looking for tools and techniques to overcome these difficulties and improve her fluency.


The first thing that would come to my mind is to increase her exposure to the language but, as I said, she already reads in and listens to English a lot. We also communicate in English with each other and we live in a country where English is not the first language, but is more or less everywhere spoken at a decent level.


Edit (after reading the comments): from my question it might appear that she's in the process of learning English as a new language. Rather the opposite: she learnt it many years ago, probably taught by incompetent teachers. The errors sedimented and now form habits that are difficult to break. That's why I say that she knows she's wrong, but she keeps making the same mistakes over again. My question would then be: are there techniques apt to change these automatic behaviours when speaking and writing?




Sunday, February 17, 2019

learning methods - Why must an English learners should know Grammar first?



Why must everyone understand Grammar first before learning to speak?




How can I implement simple object orbits in Game Maker?


I've seen a lot of tutorials for things like "fixed circular orbit" and "elliptical orbits" which end up never been what I actually want.


I have two objects: oPlayer, and oPlanet.


I am trying to allow the player to move around freely, but be able to be caught by the gravity of oPlanet, causing the player to go around in circles/elliptical orbit. I also need the player to be able to escape thate orbit, and end up on a trajectory. In fact, I want it to work for any oPlanet.


What I am looking for is something similar to the orbital gravity in Kerbal Space Program.


Is there any way I should go about this? If anyone can be of help, I would rather answers be in GML rather than the Drag and Drop, but any help is great!



Answer



I use Game Maker 8.1 all the time, and I've done orbital sims in them too. More good news: Game Maker has a built-in function that does vector addition for you:


motion_add(direction, acceleration) this will automatically change an object's hspeed and vspeed with the correct vector addition.


Remember that Game Maker treats 0 degree angle pointing right, 90 degree pointing up (which is the negative y direction), 180 deg pointing left, 270 deg pointing down. However, with motion add, you don't even need to know that.



Here's what I would do. In oPlayer, use the built-in variables x, y, hspeed, vspeed so that GM automatically does motion based on speed. Now you just need to do the acceleration from gravity, using motion_add. In the step event of oPlayer, write this:


var g, gdir; // it's necessary to make these temp vars because GM code remembers them in the scope even if you go into "with" for other objects. THIS ALSO ASSUMES YOU HAVE NO OTHER VARIABLES NAMED g OR gdir IN EITHER oPlayer OR oPlanet

with (oPlanet)
{
// this assumes each planet has a mass variable, I used 1000
g = mass/sqr(point_distance(x, y, oPlayer.x, oPlayer.y)); // handy built-in distance function
gdir = point_direction(oPlayer.x, oPlayer.y, x, y); // VERY HANDY built-in get direction function from point 1 to point 2

with (oPlayer)

motion_add(gdir, g);
}

Now in the key down events for oPlayer, for all 4 arrow buttons, put this


hspeed += 0.2; // for right arrow
hspeed -= 0.2; // for left arrow
vspeed -= 0.2; // for up arrow
vspeed += 0.2; // for down arrow

So if you hold down the right arrow, each step will add 0.2 to your hspeed. Softcode this with whatever variable name you want.



I tested this exact code myself in a GM example. The room speed was 60, oPlanet mass was 1000, and things seemed to flow at a normal pace. One orbit took 1 or 2 seconds and I could easily break or re-enter orbit by pressing the arrows.


There is 1 caveat: If the player goes too close to the planet, such as sinking beneath its surface, it will get SO close to the center that gravity becomes extremely strong, which tends to make the ship go flying off in a random direction and never coming back. To avoid this, you should make a destruction event so that the ship just crashes when it hits or goes below a planet's surface, then restart the game. Use point_distance() to test if the distance is less than or equal to the planet's radius.


Finally, like I said, I use GM 8.1. I have never used GM 9, also known as GM Studio because it looks very bloated and way, way different than the nice interface of GMs 5, 6, and 8 that I am used to.


verbs - After you took/after you take?


Let's say you are giving instruction to a person who is trying to locate his friend's house. And you say:




Go down this xxx street, then turn left onto the third street, and its just sits around the second or third house after you took the left turn



Or



Go down this xxx street, then turn left onto the third street, and its just sits around the second or third house after you take the left turn



Which is correct? Took or take



Answer



Take would be correct.


took is the past tense of take. In the example you gave in your question, you're speaking in the future tense - "You will do this, after you do that,", not "You did this after you did that."



"took" would be appropriate if you were explaining what you did in the past - "After I went down Main Street, I took a left onto Snake Oil Avenue." Since that happened in the past, you use past tense.
But when you're giving directions for someone to do in the future, you use future tense. "After you go down Main Street, you will take a left onto Snake Oil Avenue."


"took" is for when it happened in the past, "take" is for when it will happen in the future.


american english - Feel like something


1. Does the structure 'feel like doing sth' stand for a polite way of 'want' in AmE or it's British? For instance do you Americans possibly say:




  • I felt like swimming.






2. Do these sentences mean the same:




  • What would you like to drink?

  • What do you feel like drinking?



OR





  • Would you like some tea?

  • Do you feel like some tea?



I guess they should be the same and normal in AmE polite language. I was wondering if I thought properly.




terminology - What are the types of 3rd-person camera called?


I'm struggling with the terminology surrounding different types of 3rd person camera. What are the common 3rd-person camera types called? What are some notable examples of their use?




Here's what I think I've got so far:





  • 3rd Person Fixed: This type seems glued to a position behind the character. The camera and character always rotate together.


    Example: Gears of War




  • 3rd Person Free: The camera can be rotated independently of the character, so the character can continue walking in one direction while the camera is freely rotated around them.


    Example: Assassin's Creed series




  • 3rd Person Fixed-Free: This is a combination of the two above. The camera can rotate independently while the character is stationary. However, when the character starts moving, they will move in the camera's direction (not the character's direction) and rotate accordingly. Also, if the camera is rotated while the character is moving, the character will also rotate with it, as with the fixed type above.



    Example: Max Payne




Am I right?



Answer



There are no standard definitions for all the various ways in which a 3rd person camera can behave.


Your attempts at definitions are reasonable, but it would also be perfectly acceptable for a camera called a "3rd person free" camera to be entirely unconstrained to the player's location and a "3rd person fixed" camera to be one that is fixed on the player's location but can freely orbit around it.


Each game or game studio will likely use their own variation on these names.


Saturday, February 16, 2019

unity - How do you reference one game object from another?


I am trying to reference a game object that was created in the editor and added to the scene (not created dynamically). How can I reference this object in a script added to another gameobject?


For example I have a Mesh called QuantumCold_B (in the editor), and I try to get its position in a script to be added to First Person Player, but instead I get




Unknown identifier ('QuantumCold_B').



Here is my script:


function Update () {
transform.RotateAround(QuantumCold_B.position, Vector2,20 * Time.deltaTime);
}

Also is position the right way to get the Vector position on QuantumCold_B?



Answer



Since QuantumCold_B is not defined as a variable, you won't be able to use it that way.



If "QuantumCold_B" is the name of the object in the editor, you can use the GameObject.Find function to get the game object that has the name you want.


So, you would use:


var myObject : GameObject;
// This will return the game object named Hand in the scene.
myObject = GameObject.Find("QuantumCold_B");

Then, to get the position you'd use:


myObject.transform.position

I suggest you familiarize yourself with the scripting reference in general to find a lot of these types of answers on your own. Good luck!



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