Sunday, April 30, 2017

What popular/famous games are written in C?



It is very similar to this question: https://gamedev.stackexchange.com/questions/3789/famous-games-written-in-java



Does anyone know of any popular or famous games only written in C?



Answer



Doom, Quake, pretty much all id games up until id Tech 4.


graphics - Animation in OpenGL using 3D Models


I have created a model in Blender. Now i want to read that 3D model in my c++ program. I figured that a model can be exported to various file formats e.g. .obj, .3ds or COLLADA and then can be read in a c++ program. I have been searching web for doing that for quite a while and found many tutorials. But i ran into issues with most of them. For example, IN the Nehe tutorial they are using glaux which I don't want to use in my program. And the remaining tutorials use md2 which is not supported by Blender.

So can anyone guide me which file format to use for exporting 3D model and how to load that in my OpenGL program? Also how can I animate that model? Is it possible to add extra effects like tone mapping after it has been loaded in the c++ program using OpenGL? if yes then how?

P.S. I am using Linux for game developement



Answer



I'd go for OBJ format. As you have already probably realised, there's hundreds of OBJ loaders for C++ out there. I believe one of the most mature ones is Assimp, it supports many different formats and it is pretty well documented. Here you have an example where they use it.


architecture - What role does developing with events have in games?


Most application development is based around developing with events, but considering the game-loop style of developing games and the (often) need for high performance/throughput, what role does developing using events have and what are the trade-offs? Does the synchronization/locking that is often involved have a greater impact?


For instance: - How does the network [layer] notify the game-loop of data received? - How does the physics system notify of collisions


I ask, because I can remember a time when game development using events was a strict no-no. Has this changed?



Answer




Events system are powerful, and can be made very fast.


They also allow you to modulise sections of code in a very loose coupling structure. They let you job batch things and thread off tasks. The work well with multi-core and asynchronous functions.


Physics - Collision Callbacks, Activate or Rest Objects translate well to events. Networking - As much as possible should be an event (voice chat ect.. the exception) Game Logic - Naturally lends itself to an event model Menus & UI - Work brilliant in an event based system


Also many modern consoles, and middle-ware libraries use events.


The renderer and polling of input devices can be a bit confusing to fit in. Especially if you are using motion controls, as events can introduce a noticeable latency and be counter-intuitive to polling format.


meaning - Difference between will and shall



What is the difference between will and shall in modern spoken English?


For example I have the following sentences:



He will arrive on Tuesday.


He shall arrive on Tuesday.



Are there any rules specifying usage of will and shall?


Reopen note:


I looked at this question here:




But that question is about the use of the first person with will and shall. In addition one of the comments under here states that will and shall are NOT used in the same way in modern English. The linked-to question says they ARE. Which of these is correct and why?



Answer



The main use of the auxiliary verbs Shall and Will is to form the Simple Future. However these days, the use of Shall to form the Simple Future is becoming rare (especially in the US).




  1. With modern English Grammar the Simple Future is usually formed with Will.




  2. Shall is often used to make suggestions, offers or ask for advice (with questions using I and We):




    • Shall I carry your Bag? (Offer)

    • Shall I get you a cup of coffee? (Offer)

    • Shall we go out tonight? (suggestion)

    • Shall we take a break? (suggestion)

    • Shall I call again on Thursday? (Seeking Advice)

    • What shall we do with this? (Seeking Advice)




  3. Shall and Will are used to make promises, commands or threats:




    • There shall/will be no trespassing on this property. (Command)

    • You shall/will pay for this. (Threat)

    • You shall/will get your money back soon. (Promise)




  4. In American English Shall is still commonly used in Formal or Legal documents.



    • You shall abide by the law. (Legal)







For more information the references are below:
Cambridge Dictionary
Grammar-Monster.com
My English Pages


Saturday, April 29, 2017

legal - How closely can a game legally resemble another?


Most games build on other games' successes and many are downright clones. Where is the limit of imitation before legal issues come into play? Is it down to literary or graphic work like characters and storyline that cause legal problems, or can someone actually claim to own gameplay mechanics?


There are so many similar clone games out there that the rules are probably very slack or nonexistent, but I'd like to hear the views of more experienced developers / designers.



Answer



I am not a lawyer and this is not legal advice. These are things I've heard many times over and have no reason to doubt.


Game mechanics cannot be copyrighted or protected in any fashion.


I could make a game called "Crystallized" that was Bejeweled, in every imaginable way, and as long as I didn't copy the art from Bejeweled (either directly, or by drawing new art that just happens to be nigh-identical) I'd be totally fine.


Game mechanics have been copied often enough that, if this weren't the case, I have no doubt we'd have heard about it by now. Game design is pretty much one giant incestuous ball of borrowing, and, honestly, is better for it.


Keep in mind that you can be sued for anything, even if you're not breaking any contracts or laws, and they might win. But I've never heard of that happening with regards to game design.



opengl - Modern Shader Book?



I'm interested in learning about Shaders: What are they, when/for what would I use them, and how to use them. (Specifically I'm interested in Water and Bloom effects, but I know close to 0 about Shaders, so I need a general introduction).


I saw a lot of books that are a couple of years old, so I don't know if they still apply. I'm targeting XNA 4.0 at the moment (which I believe means HLSL Shaders for Shader Model 4.0), but anything that generally targets DirectX 11 and OpenGL 4 is helpful I guess.



Answer



These are all still relevant (and free online). CG tutorial (cg is virtually identical to hlsl) would probably be a good starting point.


The GPU Gems books are sorta like recipe books for random effects, they assume you know what you're doing, but they're great resources once you're more comfortable with things.


CG Tutorial


EDIT: and yeah, just about any tutorials/books you can find on shaders will still be relevant, a shader written for Shader Model 1 will run with Shader Model 4, and in a lot of cases you'll want to target lower shader models, since many effects don't need the extra stuff offered by the newer models (you can make nice water and bloom effects with SM2.0, and then if dx9 is an option you can target lower end hardware).



word usage - Difference between anyone and anybody?


As per google meaning I understood like,



Anyone - any person or any people


Anybody - anyone


It seems both are relevant. I am trying to understand the proper place for using these words. Please help me.


Thanks in Advance.



Answer



There's no difference.


Cambridge's reference:


Anyone and anybody have no difference in meaning. Anybody is a little less formal than anyone. Anyone is used more in writing than anybody:


I didn’t know anybody at the party.


[talking about the New Zealand rugby team, the All Blacks]


It is hard to find anyone who thinks that the All Blacks will face a stronger team.

subject verb agreement - Is "staff" singular or plural?


In the Cambridge Advanced Learner's Dictionary there is an example for "get by":



We can get by with four computers at the moment, but we'll need a couple more when the new staff arrive.




(Emphasis changed.)


Shouldn't this be "arrives"?



Answer



In British English staff can be singular or plural. If it is the subject of a verb, this verb is plural.



The staff in this shop are very helpful.



camera - First-person shooter -style controls



This is not in regard to a video game, but to a 3D model viewer someone else created and I am modifying.


I would like to implement first-person -style mouse and keyboard controls in the viewer, so that you can navigate through the model as if it were a house or building.


Right now, when you move the mouse up, down, left or right, the rotations are relative to the camera's coordinate axes. Which means over time you can end up with some really weird camera positions.



How do I change this to FPS-style rotations where (I think) you use latitude/longitude rotations, and the "up" direction is always perpendicular to the ground plane.


Is there a simple conversion formula I can use on the mouse input? Thanks!


(BTW, I've already implemented correct lateral camera translation. The only issue remaining is the camera rotation.)


[edit]


The article below describes my problem well, but does not provide a solution I can use since I am not using Unity.


I'm rotating an object on two axes, so why does it keep twisting around the third axis?


[edit]


Here is the function I am trying to edit. Most of it is not relevant, but you can browse through it to see what's going on. The only part I really want to change is the line with the comment "fix rotations here!!".


void LDrawModelViewer::updateCameraPosition(void)
{

float multiplier = 100.0f;
float factor = 1.0f / multiplier;
TCFloat motionAmount = 20.0f * (TCFloat)sqrt(fov / 45.0f);
/*
if (modifierKeys & MKShift)
{
motionAmount *= 2.0f;
strafeAmount *= 2.0f;
rotationAmount *= 2.0f;
rollAmount *= 2.0f;

}
*/
#ifdef WIN32
if (hrpcFrequency.QuadPart != 0)
{
LARGE_INTEGER newCount;

QueryPerformanceCounter(&newCount);
factor = (float)((newCount.QuadPart - hrpcFrameCount.QuadPart) /
(double)hrpcFrequency.QuadPart);

}
else
{
factor = (GetTickCount() - frameTicks) / 1000.0f;
}
#endif // WIN32
#ifdef _QT
factor = qtime.elapsed() /1000.0f;
#endif
#ifdef COCOA

if (FRAME_TIME != nil)
{
factor = (float)-[FRAME_TIME timeIntervalSinceNow];
}
#endif // COCOA
if (viewMode == VMFlyThrough && flyMode == FMUpSide)
{
TCVector upVector(0.0f, -1.0f, 0.0f);
TCVector tempMotion(0.0f, 0.0f, 0.0f);
TCFloat matrix[16];

TCFloat inverseMatrix[16];
TCVector::invertMatrix(camera.getFacing().getMatrix(), inverseMatrix);
TCVector::multMatrix(inverseMatrix, rotationMatrix, matrix);
TCVector tempVector = upVector.transformNormal(matrix);
if (cameraMotion[2] > 0.0f)
{
tempMotion[1] += -tempVector[2];
tempMotion[2] += tempVector[1];
}
else if (cameraMotion[2] < 0.0f)

{
tempMotion[1] += tempVector[2];
tempMotion[2] += -tempVector[1];
}
if (cameraMotion[1] > 0.0f)
{
tempMotion[1] += (1 - tempVector[2]);
tempMotion[2] += (1 - tempVector[1]);
}
else if (cameraMotion[1] < 0.0f)

{
tempMotion[1] += -(1 - tempVector[2]);
tempMotion[2] += -(1 - tempVector[1]);
}
tempMotion[0] = cameraMotion[0];
camera.move(tempMotion * motionAmount * factor * multiplier);
// fix rotations here!!
camera.rotate(TCVector(cameraXRotate, cameraYRotate, cameraZRotate) *
factor * multiplier * 1.5f);
}

else
{
//camera.move(cameraMotion * size / 100.0f * factor * multiplier);
camera.move(cameraMotion * motionAmount * factor * multiplier);
camera.rotate(TCVector(cameraXRotate, cameraYRotate, cameraZRotate) *
factor * multiplier * 1.5f);
}
}

[edit]



On a hunch, I changed that line to this:


    // Form a view vector using total pitch & yaw as spherical coordinates.
TCVector globeVector
(
cos(cameraXRotate) * sin(cameraYRotate),
sin(cameraXRotate),
cos(cameraXRotate) * cos(cameraYRotate)
);
camera.rotate(globeVector * factor * multiplier * 1.5f);


But this did not have the desired effect.


[edit]


Okay, I replaced the previous code with:


    TCFloat identity[16];
memcpy(identity, TCVector::sm_identityMatrix, sizeof(TCVector::sm_identityMatrix));
TCVector::calcRotationMatrix(cameraXRotate, cameraYRotate, identity);

But I get an error that TCVector::sm_identityMatrix is inaccessible.


Also, how do I feed the new matrix back to the camera? The camera.rotate method only takes a three component vector as input AFAIK. I was unable to locate any documentation on the camera object, and the code has few comments in it.




Friday, April 28, 2017

learning - How to overcome sequences of negative words which still cripple my comprehension?


Despite my attempts and *surplus of questions (since joining ELL), sequences of negative words still annihilate, lame, squash my reading comprehension. So how can I decisively vanquish this paralysis/scourge, productively on a general scale? What do I lack? I asked about the relevance of logic.


*These are listed in this exemplifying question and When do multiple negatives cancel and when do they not?.




Thursday, April 27, 2017

terminology - What is the common term for the word "menstruation"?


What is the common term for the word "menstruation"?


Can I use cyclus?


In my native language, we normally say it by "monthly guest".




What is the expected response to "What's up?"


When somebody ask me What's up? I answer I am well, thank you.


Is that the expected answer, or should I answer something else?
What does a native speaker understand when I reply like that?



Answer




Ah, this phrase is all about context. The meaning of "What's up?" and expected responses depend on the circumstances in which the question is asked.


From what I remember, the phrase is derived from "What's the update?" which is basically checking up how things are going. It has however fallen into common usage both in the US (I think) and UK.


As a greeting:


"What's up?" or here (West Midlands of England) commonly just "sup" is a general greeting, you can response with answers like "Not much", "Nothing", "Alright" etc.


In this context, the response is just a return of the greeting, or a confirmation that all is going normally. This phrase is similar to "Hello" or "How are you" in common usage.


Example:



Person 1: "What's up man?"


Person 2: "F*** all mate" (my typical response to friends, this means nothings going on and I'm bored because of it :^) )




As an enquiry


In this context, "What's up?" can be when the asker of the question may have observed someone having some trouble, or is distressed at something.


It's a polite, non-intrusive way of checking all is relatively okay or if they need assistance. A similar phrase would be "What's the matter?" or "What's the problem?".


When facing criticism or disapproval of something, a common phrase is "What's up with it?" meaning the asker is not sure what they have done wrong and wants to know what said issue is.


Example:



Person 1 notices Person 2 with their head in their hands at their desk


Person 1: "What's up?"


Person 2: "Nothing, just tired."




So to properly answer your question after rambling a bit. The idea behind "I am well" is sort of right - you are confirming that all is well and normal. So in this case "Nothing" or "Not much" or "Same Old" are all fine, and will be understood by a native speaker.


Personally, if I was speaking to a non-native English speaker and heard your response I wouldn't think anything of it - it's just a throwaway question so unless something really is up/wrong, the response is irrelevant.


game design - Developing an ELO like point system for a multiplayer gaming site


I'm currently working on a gaming site where users will submit virtual players for different games, like Chess, Nash, Backgammon, Go, etc. The idea is that users don't compete themselves, but through their virtual players. There will be leagues, tournaments, and other competition formats.


The question is which would be a good rating system for users in this environment. Take into account that every user may have many different virtual players playing in many different games. As a general guideline I would like to guarantee the following properties:



  • Users who have a lot of mediocre players should not score higher than users with a few very good players.

  • A user with a high rating should not be penalized if he adds a new bad player, until he has had enough time to improve his player.


  • Users who don't play often should not score higher than users who play every day.


Thanks in advance.



Answer



I would divide the ranking into 3 levels:




  1. Bottom level is where players are rated. Use ELO or a similar system, where a strong player is penalized much more for loosing with a weak opponent, than he could be awarded. Also secure game system for users using many accounts, e.g. by random matchmaking. This will solve your 3rd point:





    • Users who don't play often should not score higher than users who play every day.





  2. Middle level is rating for every group of players owned by one user and playing one game, e.g. Alejandro's Chess players. You most probably don't want a chess player to play with a Go player, as they use different algorithms, and even the best player of one game will probably lose with one of the worst players in another. To calculate the rating of a group, take an average of ELO of the players in the group, not considering 20% of the worst players in this group. This will ensure the extraordinarily terrible players won't affect average rating. Keep in mind this is yet another reason to make matchmaking random. So this covers two remaining points of your requirements




    • Users who have a lot of mediocre players should not score higher than users with a few very good players.

    • A user with a high rating should not be penalized if he adds a new bad player, until he has had enough time to improve his player.






  3. Top level is rating for a user. This is a very subjective part; you could for example:



    • show best achievement of the user (#23 place in silver league)

    • show average of scores of all game-groups

    • show average of scores of all game-groups the user is active in

    • show the highest of scores of game-groups


    • calculate the main score in a complex way, e.g. find the highest possible score of a user, being an average of chosen groups plus 100 bonus points for every group taken into an average.




plural forms - "Number" or "numbers"?


Is there a difference between using "number" and "numbers" when referring to multiple numbers?


For example, when calling a merchant to inquire about multiple orders, should I say:



I need RMAs for order numbers 1 and 2.




or



I need RMAs for order number 1 and 2.



This question might sound stupid, but I'm not sure what the main subject is. Is "number" the subject and therefore should I use "numbers"? Or are the order numbers (1 and 2) the subject, so should I keep "number" singular?



Answer



I usually hear that as "Order numbers 1 and 2", with the "s". Fumble's comment gives a good way to get around it anyway.


inversion - Where is the subject in "[...] weaker than would otherwise have been the case"?


Where is the subject in the following dependent clause?



[...] Germany adopted a much weaker currency than would otherwise have been the case [...] (taken from BBC News)



Is "the case" the subject? I don't think so. Imagine I re-write the sentence as:




Germany adopted a much weaker currency than would otherwise have been possible



My inability to tell what is the subject in those sentences makes me feel there is something wrong?


If I try to find the subject by asking: "what would it otherwise have been the case?", I would answer the subject is "that Germany adopted a much stronger currency".


The meaning is clear but the grammar feels wrong.


Could anyone explain the grammar involved in this sentence?




ADDITIONAL QUESTION


This n-gram shows that "than it would otherwise have been" is never used.



Is it wrong to write the following? If so, why?



Germany adopted a much weaker currency than it would otherwise have been the case




Answer



In ‘A Student’s Introduction to English Grammar’, Huddleston and Pullum write that there are three major subclasses of dependent clause. One of these subclasses is the comparative clause. Here’s their example:



More people came than had been invited.



They further note that this clause “has no overt subject at all.” Your sentence seems to be a similar case. We might think the clause is based on “people had been invited”, as for your sentence “it would otherwise have been the case.” But “people” and “it” cannot appear.



Again according to Huddleston and Pullum, one of the distinguishing features of this type of clause is that “they are obligatorily reduced in certain ways relative to the structure of main clauses.” (p. 201) It seems that subjects, predicative complements or degree modifiers just have to be left out, and the sentence in question is one case of this.


Edit: If we take the underlying form as “the case would otherwise have been [that Germany adopted a stronger currency]”, then this would be SV inversion in the comparative clause as @Nico suggests. However, “it was the case that X” seems more natural to me than “the case was that X”. Therefore I would still prefer to treat this as omission of the dummy subject “it” rather than inversion.


path finding - what is the standard solution to pathfinding towards a moving target?


I am working on a 2D RTS like game, basic A* works perfectly for moving a unit from point A to point B.


But now I facing the continuous path-finding problem, like A attack a moving object B, call A* at each frame once Object B's position changed seems inefficient.


so what is the standard method to this problem?




Wednesday, April 26, 2017

What tools/software are used to make the environments/levels/maps in games?



This question has probably been answered before but I've not been able to find the answer, since I'm not able to frame the question with brevity.


So the whole question is :- The worlds/levels that you see in games like Crysis, Assassin's Creed, etc, what do the designers and developers use to create them? Do they use the tools present inside the engine (whether proprietary or in-house) or a separate software that exports these worlds as an importable object for the game engine to use to load models into it, etc?



I know this is a very general question but I have been curious regarding this for some time. I have used Unity in the past and it had a terrain toolkit that could be used to make the terrain, and I'm pretty sure it had completely to do with my lack of skill but I wasn't even close to making an environment that looked like the ones you see these days.



Answer



Typically, in both triple-A and indie games, the developers will develop a set of tools for map and level for their game themselves. Take The Elder Scrolls V: Skyrim as an example, the creation kit is basically a level editor as with it you're able to edit the world of Skyrim. When the develops made the world and levels of Skyrim that would have used a slightly different version of the creation kit (since I think they altered it for public release). Skyrim Creation Kit


A lot of games nowadays are developed using the Unreal Game Engine (both indie and triple-A), which has its own editor http://www.unrealengine.com/features/editor/


And since you mentioned Crysis. Crytek have developed their own engine and development kit called the CryENGINE, which they obviously used to build Crysis, you can read about it here: http://www.crytek.com/cryengine/cryengine3/overview


The use or omission of commas round relative clauses


In Longman English Grammar Practice, there is a practice question in which you would say what the sentences mean with and without commas.




My brother who is in Canada is an architect.



Without commas: I have another brother or other brothers somewhere else.


With commas: I have only one brother.


I am perplexed by this. How do you come to this answer? I thought the whole use of commas in this instance was to provide additional, unnecessary information. If there are commas used, then it means that him living in Canada is just additional information that has no relation to him being an architect. If commas are not used, then him living in Canada is important for him being an architect. Please correct me if I am wrong.




State changes in entities or components


I'm having some trouble figuring how to deal with state management in my entities.


I don't have trouble with Game state management, like pause and menus, since these are not handled as an entity component system; just with state in entities/components.


Drawing from Orcs Must Die as an example, I have my MainCharacter and Trap entities which only have their components like PositionComponent, RenderComponent, PhysicsComponent.


On each update the Entity will call update on its components. I also have a generic EventManager with listeners for different event types.


Now I need to be able to place the traps: first select the trap and trap position then place the trap.


When placing a trap it should appear in front of the MainCharacter, rendered in a different way and following it around. When placed it should just respond to collisions and be rendered in the normal way.


How is this usually handled in component based systems?



(This example is specific but can help figure out the general way to deal with entities states.)



Answer



One interesting application of a component system is that you can change an entity's components at runtime if you designed it to be able to handle such. The state of an entity thus becomes the sum of both which components are assigned to it and which values those hold.


For your example, you can first create the trap with a BuildControllerComponent (governing the reaction to player controls in build phase), a PositionComponent and a RenderComponent. The last one has one data field which governs the pixel shader(s) used, and one of them gives the trap-to-be-build a "ghostly" look. You'll notice there are no physics components assigned yet.


Upon placing the trap, the components get exchanged. The BuildControllerComponent isn't needed anymore, so it gets removed. The RenderComponent's shaders get replaced with your normal standard view of the trap. Finally, PhysicsComponent as well as whatever else is needed for the trap to work are added to the entity.


In an inheritance-based approach, this is equivalent to having a constructor for an ActiveTrapEntity class which takes a BuildTimeTrapEntity class as its arguments, the second one being used to render the trap during building it, the first one being used for the trap after it's in place.


physics - AS3/Flash Develop - Radial Gravity (character on planet simulation)


I am trying to create a program where a character shape will be constantly drawn towards the centre of a planet shape. I have taken on previous advice into using physics equations to generate the desired effect yet I think I am missing some and therefore it does not work (I am only using v^2=u^2+2as). Am I over complicating things? All I need is for the player object to be constantly drawn towards the centre of the planet object; there will be no need for other planet objects to come into play and affect the player's gravity.


edit: To clarify, my question should have been "where did I go wrong?". I have now since solved the problem with the answers posted below, which were present because I wasn't going about trying to achieve what I wanted the right way. I didn't calculate the actual direction to move in as expected, and so the character could not move in the expected direction.


Here is my Main.as:


package
{
import flash.display.InteractiveObject;
import flash.display.Sprite;

import flash.events.Event;
import Math
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.events.KeyboardEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.*;

/**

* ...
* @author Me
*/
public class Main extends Sprite
{
public var planet1:Planet;
public var character1:Character;
public var initialXVelocity:Number = 0;
public var initialYVelocity:Number = 0;
public var finalXVelocity:Number;

public var finalYVelocity:Number;
public const gravitationalAcceleration:Number = 3;
public var xDistance:Number;
public var yDistance:Number;



public function Main()
{
if (stage) init();

else addEventListener(Event.ADDED_TO_STAGE, init);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
planet1 = new Planet;
character1 = new Character;


//place entites in position to test note: planet 1 is 100*100 pixels, character 1 is 10*10 pixels
planet1.x = 350;
planet1.y = 250;
character1.y = 100; //295
character1.x = 396; //395
addChild(planet1);
addChild(character1);

//Make sure character has gravity applied constantly
setInterval(playerMove, 1000);


}

public function playerMove():void
{
//Calculate the distance between the character and the planet in terms of x and y coordinate
xDistance = (character1.x + 5) - (planet1.x + 50);
yDistance = (character1.y + 5) - (planet1.y + 50);

//Make sure this distance is a positive value

if (xDistance < 0) {
xDistance = -xDistance;
}

if (yDistance < 0) {
yDistance = -yDistance;
}

//Calculate velocity using physics equation v^2=(u^2)+2as
finalXVelocity = Math.sqrt((initialXVelocity * initialXVelocity) + (2 * gravitationalAcceleration) * xDistance);

finalYVelocity = Math.sqrt((initialYVelocity * initialYVelocity) + (2 * gravitationalAcceleration) * yDistance);
/*trace(initialXVelocity);
trace(gravitationalAcceleration);
trace(xDistance);
trace(finalXVelocity);
trace(initialYVelocity);
trace(gravitationalAcceleration);
trace(yDistance);
trace(finalYVelocity);*/


//Make sure the character is moving towards the centre of the planet at all times by reversing the appropriate velocity once it passes the axis of the centre of the planet
if (planet1.x < character1.x) {
finalXVelocity = -finalXVelocity;
}

if (planet1.y < character1.y) {
finalYVelocity = -finalYVelocity;
}

//Update the current velocity before new velocity is calculated

initialXVelocity = finalXVelocity;
initialYVelocity = finalYVelocity;

//Send the character into the correct direction
character1.x += finalXVelocity;
character1.y += finalYVelocity;
}

}


}


Tuesday, April 25, 2017

determiners - How do I know when to use "the" versus "a" versus "∅" as an article on a noun?



With proper nouns, we don't use the except for river names, newspaper names, etc.


I want to know why we use the with White House. I mean, under which rule can we categorize it? What could other similar examples for that rule be?



Answer



In general, we tend to use the as an article for nouns and proper nouns where it is clear from context that only one thing belongs to that description (or when we are talking about the archetypal thing of a set of things in the abstract). Otherwise we would normally use a to signify that we mean a single element out of a group of things that all fit the description.


General rules for articles


For example:



The President of the United States is Barack Obama.



There is only one sitting US President, so the is the correct article to use here, but...




President Obama is a Democratic President.



There is more than one President from the Democratic Party, so a fits better here.



The most populous country is China.



*We use the here because there is only one "most populous country"*.



The President lives in the White House




Although there are many houses that are white, and there are even several copies of the famous White House, the context here makes it pretty clear which one we're talking about, and there's no ambiguity. Similarly it is clear which President we are talking about from context, and there's only one that fits the context.


This isn't even limited to proper nouns:



I'm going to turn on the TV



Although there are many TVs in the world, it is clear from context which one I mean.



I am looking forward to the launch of the PlayStation 4




*The second the here is talking about the singular product called "PlayStation 4", of which there is one (even though there are many units that will be sold), and the first the refers to the singular event which is the launch of that product*.



I own a PlayStation 3



Since I own only one of many PlayStation3 units


Rules for omitting articles


Here are some rules of thumb that will help you get by.



  1. Items with numerical count or position normally have articles omitted (more detail)




I came first in the pie-making contest!


(X) I came a first in the pie-making contest!


(X) I came the first in the pie-making contest!


Here are six apples.


(X) Here are a six apples.


(X) Here are the six apples.



Unless you are specifically referring to this group, which should be clear from context:




Here are the six apples [that we were talking about earlier].





2: Avoid putting adjectives on noun-phrases with omitted articles, but if you do prefix with an adjective, the article must be reintroduced:



Buckingham Palace is world-famous!


We visited the world-famous Buckingham Palace yesterday!



Except when talking about countries:




Join us on our exciting tour of historic China!





3: Never omit an article if the noun-phrase contains of:



The British Parliament sits in the Palace of Westminster.


The British parliament sits in Westminster Palace.





4: Always omit articles when talking about people by name.




(X) I love the Oprah Winfrey.


I love Oprah Winfrey.



But not, if the name of the individual is just part of a noun-phrase that isn't a person:



I love the Oprah Winfrey show


(X) I love Oprah Winfrey show






5: Omit articles when talking about companies by name or the buildings named after them.



She works at Microsoft.


(X) She works at a Microsoft.


(X) She works at the Microsoft.



When there are many places that share the same company name (e.g. McDonalds, Starbucks), then you can either omit the article, or use a. You can also always use the when talking about a specific place that is clear from context.



I work at Starbucks. (good)


(X) I work at the Starbucks. (not acceptable without context).



I work at the Starbucks [that we were talking about before].


I work at a Starbucks. (acceptable).





6: When talking about the singular names of most continents, territories, islands, settlements (including cities, towns, ports, villages, forts, and garrisons), states, lakes, waterfalls, bays, mountains, languages, sports, academic subjects, or street names we omit the article:



I visited London, which is in Europe.


(X) I visited the London last year.


We went to the Himalayas to climb Everest!


We'll meet at the top of Victoria Street and then we'll go to Brixton later.



The Great Lakes is a collection of lakes, so has an article.



But there are exceptions that must be learned by rote, such as



The International Criminal Court is based in the Hague.


I grew up in the Bronx.





7: We usually omit the article when talking about countries:


Some countries omit the, some don't. By default, the article is omitted, but it is reintroduced if:




  • The country name is derived from a plural:



The United States, the US (but not America), The United Kingdom, the UK (but not Great Britain, England etc), the USSR (but not Russia), The United Arab Emirates


The Azores, the Canaries, the Falklands, the Galapagos, the Bahamas, the Dao Yu Islands


The Philippines, the Netherlands.


The Russian Federation, The British Empire, The Roman Empire.





  • Remember: if the country is being given its full name including style of government, it regains an article by rule (3) above.



The People's Republic of China (but "I visited China")


The Islamic Republic of Iran (but "Iran is a beautiful country").



And there are a whole bunch of random exceptions:



The Vatican has an article, but Vatican City doesn't.


The Gambia uses an article, although it is sometimes used without one.



The Democratic Republic of the Congo is often (unofficially) called "The Congo".


Before 1991, Ukraine was referred to as the Ukraine (short for "the Ukrainian Soviet Socialist Republic"), but now has no article. In the mid 20th Century, "The Argentine" became known as Argentina.


We used to say "The Lebanon" (from the literal translation of HaLevanon), but now "Lebanon" is normally given with no article.





8: Some nouns are used without articles to indicate that they are being used in idiomatic form:



She went to bed (means she went to her bed in order to sleep)


She went to work (she went to her workplace to perform her job).


She went to school/university/college (means she attended her school. Also variants such as Summer school and Sunday school can be used this way.)



She went to church (means she attended church. Other religious places cannot be used this way. Articles are normally used for "He went to the temple/cathedral/mosque/synagogue etc")


She went to war (means she went to fight as part of the military abroad).


She went to prison/jail (means she was convicted of a crime, and was incarcerated).


She went to hospital (she was admitted to hospital. esp. British English).


She went to court (she was brought before a judicial court, either as the plaintiff or as the defendant, or possibly as a lawyer or judge presiding).



These nouns can be used with articles when the idiomatic form is not wanted and we want to refer to the noun in it's "ordinary" form:



The bed is broken.


The church is next to the synagogue.



The war in Iraq started in 2003.


I went to the prison in order to better understand the psyche of the inmates. (as opposed to I went to prison in order to..., which would imply that the speaker was incarcerated, rather than just visited).


I went to the hospital on Tuesday to pick up Auntie May.



These forms just need to be learnt.




9: Most names which are constructed from a possessive form of a person, city, county or suburb drop the article.



We visited Beeston Castle the other day!


Nelson's Column is 169 ft 3 in tall!



Queen Elizabeth I is buried at Westminster Abbey.


Kensington Gardens are very famous.


Seattle Tower is more commonly known as "The Space Needle".


Munich Cathedral is very impressive.


I'm writing a letter to Westminster City Council.


Sydney Opera house is amazing!


We visited St. Paul's Cathedral on Tuesday.



But




The Science Museum and the Natural History Museum are right next to each other.


The Tate Modern is quite expensive, but well worth the trip.


The British Library is free.





10: Nouns which are personal qualities are usually given with no article (see StoneyB's answer here)



He certainly has talent. (He is talented)


Nobody denies her courage. (She is courageous)


Sartorius lacks generosity. (Sartorius is not generous)






11: Most other nouns take an article, and the ones that don't tend to inconsistently have their articles used or not used by native speakers, so don't worry too much about them, and learn them by rote as and when they come up.


For example:



The Wikipedia article on Hagia Sophia uses the article "the" for Hagia Sophia 23 times but omits it 22 times.


"Taj Mahal" normally takes an article, but the official website uses both forms.


The Washington Monument / The Lincoln Memorial normally (but do not always) take articles.






(X) Signifies poor usage.


Past tense vs. Present Perfect tense



I was reading the book "Essential Grammar in use" Third Edition by Raymond Murphy.



In page no.56, there were some questions about using Past Tense and Present Perfect Tense. In that, one question confused me a little. I've given it below,



The washing machine was broken, but it's OK now. It __________ (repair).



My answer at first sight was "was repaired" (wrong answer) because I thought the action was completed in the past.


But the correct answer given in the book was "has been repaired". It confused me a little. However, I understood it later that the action's result "It's OK now" has been related to the present. So the answer "has been repaired" seemed correct to me.


However I always confuse this below examples,



"I sent an email to you yesterday."


"We despatched a parcel to you yesterday."




vs.



"I have sent an email to you."


"We have despatched a parcel to you."



The first one should be the most common or correct answer. But what's wrong with the second one? Can I use it? Because the mail sent / parcel despatched has some connection with the Present, because it hasn't reached them yet.


Also please clarify, whenever I use Past tense, Is it always required to tell the time of action? Eg. "I sent an email to you yesterday."


I have already asked similar questions here. But still, I have some little confusions. As a non-native English speaker, most of the time, I think that something I did in the past has some connection with the present moment and I feel like I need to use " Present Perfect".


Please help me. Thanks in advance.



Update:


This question has been marked as duplicate. The other question was also asked by me. However this one is different & more in detail than the other question. That question was about the time markers (yesterday) with Present Perfect tense. But this is about no time markers, but I'm asking that, is it OK to use Present Perfect tense when the action was happened some hours ago however the action is still connected to the present moment.



Answer



Being a non-native speaker, I too had the same confusion. However, by observing lots of examples and reading answers here, on this site, I can now be clear! I'll try to solve this for you.


It is actually the context that decides what to use when! But, please note that there are no concrete rules for what I'm saying.


Let's create a scene at some office.


There is an email regarding 'refund' from one of your clients, and this needs to be addressed immediately. You forward that mail immediately to the salesperson. You now call him and say:



I have sent you an email of Mike. Please look into the matter immediately.




Now, think that the mail had no urgency. After 4-5 hours you are meeting the salesperson and just informing/confirming about the email. You say:



I have sent you an email a couple of hours back. Did you check it?



If the matter is serious and things are ignored. In other words, there was no reply from your sales department to the client. You now emphasis that the mail is with the salesperson since quite long. Now here, quite long could be just 3 hours as well, but the delay is unpardonable. Had/have both can work. You angrily say:



I have/had sent the mail two hours ago, and still there is no reply! The client is angry.



If it is the next day, you may use had because it's now a distant past.




I had sent you an email yesterday. Please check, and go for push notification.



Again, to repeat, there is no strict rule I have come across. Depending on the situation, you use 'have/had' or neither of them. However, as I said, it will look down to me if you use 'have' and refer to the mail sent yesterday!



I have had sent you an email yesterday.



If I try to remember all the instances, I can also say that you use nothing (no had/have) while narrating the case or matter to someone. However, this could be common only in informal talk.



You know what happened yesterday? Mike, one of our clients, shot an email to me and he was completely pissed off! He wanted a refund, and the matter was pending for more than a month! I then forwarded the mail to Andrew and thankfully, all was settled.




No had/have there!


past perfect - Tense agreement: "Before he 'had come'/'came' to the factory, Tom 'was studying'/'had studied' at the university of London"


Which of the following sentences is correct?






  1. Before he had come to the factory, Tom was studying at the university of London.




  2. Before he came to the factory, Tom had studied at the University of London.







articles before numbers


1. Around the World in a Hundred Years: From Henry the Navigator to Magellan


2. A Thousand Years of Nonlinear History


These are the titles of books. I would like to ask why the indefinite article is used before the number. When omitting the article would the meaning be different?



Answer




We would not say


Around the World in a Eighty-Six Years.


When dealing with common units of measure: hundreds, thousands, dozens etc., we use the article.


A dozen years


A hundred years


A million years


A thousand years


unity - How can I create Portrait game assets to have same with gap for both iPhone 7 Plus and iPhone X?



In my Unity game I made changed my Pixel Per Unit value to 243 since the height of a Portrait game for iPhone X is 2436. The game looks great and the asset sizes look just right on the iPhone X simulator. But when I change to iPhone 7 Plus I get considerable space on the sides and it gets worse when I change to the iPad. How can I make my game have the same width gaps for iPhone 7 Plus and iPhone X without making assets look stretched horizontally or vertically?


UPDATE


The images below give an idea of my game on both 1080x1920 (for iPhone 7 Plus) and 1125x2436 (for iPhone X). It's not a match3 game. All the game objects below are static and have colliders. The gaps between are quite significant for other dynamic objects to move between. Reducing the gaps significantly would alter the movement of the dynamic objects and their sizes too, making the ratio in object sizes look wrong. I haven't started worked on scores or menus yet, so I haven't added a UI canvas yet.


enter image description here


enter image description here




unity - Displaying Trajectory Path



How can I display trajectory path exactly as in this image?


I have used void OnDrawGizmos, but that only displays trajectory in the editor and without any arrows like shown below.


enter image description here



Trajectory with void OnDrawGizmos


enter image description here


Script:


public Transform someObject; //object that moves along parabola.
float objectT = 0; //timer for that object

public Transform Ta, Tb; //transforms that mark the start and end
public float h; //desired parabola height

Vector3 a, b; //Vector positions for start and end


void Update () {
if ( Ta && Tb ) {
a = Ta.position; //Get vectors from the transforms
b = Tb.position;

if ( someObject ) {
//Shows how to animate something following a parabola
objectT = Time.time % 1; //completes the parabola trip in one second
someObject.position = SampleParabola( a, b, h, objectT );

}
}
}


void OnDrawGizmos () {

//Draw the parabola by sample a few times
Gizmos.color = Color.red;
Gizmos.DrawLine( a, b );

float count = 20;
Vector3 lastP = a;
for ( float i = 0; i < count + 1; i++ ) {
Vector3 p = SampleParabola( a, b, h, i / count );
Gizmos.color = i % 2 == 0 ? Color.blue : Color.green;
Gizmos.DrawLine( lastP, p );
lastP = p;
}
}


#region Parabola sampling function
///
/// Get position from a parabola defined by start and end, height, and time
///

///
/// The start point of the parabola
///
///
/// The end point of the parabola
///

///
/// The height of the parabola at its maximum
///
///
/// Normalized time (0->1)
/// S
Vector3 SampleParabola ( Vector3 start, Vector3 end, float height, float t ) {
float parabolicT = t * 2 - 1;
if ( Mathf.Abs( start.y - end.y ) < 0.1f ) {
//start and end are roughly level, pretend they are - simpler solution with less steps

Vector3 travelDirection = end - start;
Vector3 result = start + t * travelDirection;
result.y += ( -parabolicT * parabolicT + 1 ) * height;
return result;
} else {
//start and end are not level, gets more complicated
Vector3 travelDirection = end - start;
Vector3 levelDirecteion = end - new Vector3( start.x, end.y, start.z );
Vector3 right = Vector3.Cross( travelDirection, levelDirecteion );
Vector3 up = Vector3.Cross( right, travelDirection );

if ( end.y > start.y ) up = -up;
Vector3 result = start + t * travelDirection;
result += ( ( -parabolicT * parabolicT + 1 ) * height ) * up.normalized;
return result;
}
}

Answer



As your desired image reflects that you want it in 2D, so I have modified your current script which would draw a path from your given Game Object, decided start position, mouse or finger position would be the end position. Other than that you can specify number of elements should be drawn on the path.


Well, have a look and give it a try. Comments will also help you a little bit.


using UnityEngine;

using System.Collections;
using System.Collections.Generic;

public class Test5 : MonoBehaviour
{
public Transform _moveableObject; // Objet to move on path
public GameObject _trajectoryElement; // GO to draw in path of trajectory. GO having signle white arrow attached on it
public Transform _startPosition; // Start position from where trajectory should start and mouse of finger position is the destination
public float _height; //desired parabola height
public int _numberOfElements = 10; // Number of elements should draw in path of parabola


Vector3 a, b; //Vector positions for start and end
List _trajectoryElementsContainer = new List ();

void Start ()
{
// For now I have instantiated all the objects will be drawn on the path of parabola. Then did handle them later.
// Please modify it according to your needs
for (int i = 0; i < _numberOfElements; i++)
_trajectoryElementsContainer.Add (Instantiate (_trajectoryElement) as GameObject);

}

void Update ()
{
if (Input.GetMouseButton (0) && _startPosition) {
a = _startPosition.position; //Get vectors from the transforms
a = new Vector3 (a.x, a.y, 0);
b = Camera.main.ScreenToWorldPoint (Input.mousePosition);
b = new Vector3 (b.x, b.y, 0);


float distributionTime = 0;
for (float i = 1; i <= _numberOfElements; i++) {
distributionTime++;
Vector3 currentPosition = SampleParabola (a, b, _height, i / (float)_numberOfElements);
_trajectoryElementsContainer [(int)i - 1].transform.position = new Vector3 (currentPosition.x, currentPosition.y, 0);

Vector3 nextPosition = SampleParabola (a, b, _height, (i + 1) / (float)_numberOfElements);
float angleInR = Mathf.Atan2 ((nextPosition.y - currentPosition.y), (nextPosition.x - currentPosition.x));
_trajectoryElementsContainer [(int)i - 1].transform.eulerAngles = new Vector3 (0, 0, (Mathf.Rad2Deg * angleInR) - 90);
}


if (_moveableObject) {
//Shows how to animate something following a parabola
_moveableObject.position = SampleParabola (a, b, _height, Time.time % 1);
}
}
}


void OnDrawGizmos ()

{

//Draw the parabola by sample a few times
Gizmos.color = Color.red;
Gizmos.DrawLine (a, b);
float count = 20;
Vector3 lastP = a;
for (float i = 0; i < count + 1; i++) {
Vector3 p = SampleParabola (a, b, _height, i / count);
Gizmos.color = i % 2 == 0 ? Color.blue : Color.green;

Gizmos.DrawLine (lastP, p);
lastP = p;
}
}

#region Parabola sampling function
///
/// Get position from a parabola defined by start and end, height, and time
///

///

/// The start point of the parabola
///
///
/// The end point of the parabola
///
///
/// The height of the parabola at its maximum
///
///
/// Normalized time (0->1)

/// S
Vector3 SampleParabola (Vector3 start, Vector3 end, float height, float t)
{
float parabolicT = t * 2 - 1;
if (Mathf.Abs (start.y - end.y) < 0.1f) {
//start and end are roughly level, pretend they are - simpler solution with less steps
Vector3 travelDirection = end - start;
Vector3 result = start + t * travelDirection;
result.y += (-parabolicT * parabolicT + 1) * height;
return result;

} else {
//start and end are not level, gets more complicated
Vector3 travelDirection = end - start;
Vector3 levelDirecteion = end - new Vector3 (start.x, end.y, start.z);
Vector3 right = Vector3.Cross (travelDirection, levelDirecteion);
Vector3 up = Vector3.Cross (right, travelDirection);
if (end.y > start.y)
up = -up;
Vector3 result = start + t * travelDirection;
result += ((-parabolicT * parabolicT + 1) * height) * up.normalized;

return result;
}
}
#endregion
}

NOTE: This script is not in proper way and un-optimized. Please make it better for performance sake. (if needed)


Edit: The "- 90" factor is here (in last line of update)due to my arrow image is originally vertical (pointing upward/sky) that is why it is balancing the angle. This script is also expecting from you that if you give white arrow like you have shown in question, then try to rotate it from outside the Unity as it should point to the sky otherwise you'd have to play with that "- 90" factor :)


Monday, April 24, 2017

meaning in context - Why does he go "pink with the effort" while watching morris dancing?


This is a follow-up question to my previous one, WHY did he go slightly “pink” ?? Does it mean angry, embarrassed, healthy or other meaning in this sentence?, as in that one I have established that "pink" in this context mean "embarrassed" other than "angry or healthy."


Then it leads to my second confusion, why is he embarrassed? I have checked the definition of morris dance on wikipedia, so far as I know it's a culture dancing, some cultural heritage. but why embarrassing? is there some culture gap I have missed??


Here is the sentence:




We, in the meantime, had gradually been increasing Will’s outings—and the distance that he was prepared to travel. We had been to the theatre, down the road to see the morris dancers (Will kept a straight face at their bells and hankies, but he had gone slightly pink with the effort), driven one evening to an open-air concert at a nearby stately home (more his thing than mine), and once to the multiplex where, due to inadequate research on my part, we ended up watching a film about a girl with a terminal illness.


Me Before You by Jojo Moyes



I searched the whole novel, and there are only two times "morris" are mentioned, the other is in a conversation in a horse racing watching:



‘Don’t be grumpy. They say you should try everything once,’ I said.


‘I think horse racing falls into the “except incest and morris dancing” category.’


‘You’re the one always telling me to widen my horizons. You’re loving it,’ I said. ‘And don’t pretend otherwise.’


Me Before You by Jojo Moyes




The context is that Will is a quadriplegic in wheelchair and he rarely goes out, and he does not like go watching horse racing. "We" means Louisa, his carer.


Could anyone help with this question?



Answer



To augment Jeff's answer...


"To keep a straight face" means to refrain from laughing or grinning; to succeed in an effort not to laugh despite the urge to do so.


Morris dancing dates back to well before Shakespeare's day. It is not a mainstream tradition that nearly everyone enthusiastically engages in; rather it is a form of folk dance being kept alive by local troops and by clubs on university campuses. The practice is regarded by many as hopelessly quaint and silly.


word usage - Could you clarify when to use "Though" at the end of a sentence?


Ok, English textbooks mostly teach the structure "Although / though",


for example,





  • Although my wife and I are so busy,we spend time together every weekend.





  • Anne was fond of Tim, though he often annoyed her.





However, in reality, I heard a lot of people use "though" at the end of a sentence.


So, I checked the dictionary & found that "Although" & "Though" in the above examples are conjunction.


But, from OALD, "Though" is used especially at the end of a sentence to add a fact or an opinion that makes the previous statement less strong or less important


Example:




Our team lost. It was a good game though.



But, for me, It seems that "Though" that is used at the end of a sentence is more popular than "Though" that is used at the start of a sentence.



Answer



First off, we must remember that "though" can be used as a conjunction and adverb, whereas "although" is a conjunction; it's never an adverb. So "although" and "though" are only interchangeable when they are used as a conjunction.


As a conjunction, "though" is much more common than "although" in speaking.


When used as a conjunction, "though" or "although" can be used at the start of a subordinating clause whether this clause comes before or after a main clause.


As for the "though" as an adverb meaning however, you usually use it at the end of a sentence.


In the sentence "It was a good game though" presented by the OP, the "though" has been used as an adverb.


Prevent cheating in html Javascript game



I have made a Javascript/html game. Now the problem I have is anyone can edit the client code and cheat in game for example there is a man shooting a enemy.



  • Man HP:          100

  • Enemy HP:      50






Now if someone changes the hp attribute to a very high value then he becomes literally immortal making the game easy. Now how can I prevent this type of thing ?



Answer



You can't.


Javascript is executed on the users machine. Whatever is executed on the client side can be manipulated by the client. All mainstream web browsers come with powerful debugging tools out-of-the-box which allow users to influence Javascript code even more than with the console. So the user doesn't even need any special software tools like they would for cheating in games implemented as binary executables.


You could try to minify and obfuscate your code beyond recognition (there are tools for that which you can integrate into your deployment script), but a determined hacker can still find out where you are hiding the important data. So you might slow them down, but you can not stop them.


The only way to prevent cheating in a web-based game is to implement all important game mechanics on a server where it is out of reach for the user.


But keep in mind that when your game has no multiplayer component or global leaderboards, then it is questionable if any work invested in preventing cheating is really providing any benefit. Cheaters can only hurt their own game experience while the honest players who want to play the game as designed won't be affected at all. Allowing a bit of cheating can even enhance the game experience because it allows players to experience the game in a different way. There is a reason many game developers intentionally add cheat codes or developer consoles to their games.



grammaticality - Can "Monday", "Tuesday" be plural like "Mondays" or "Tuesdays"?



Which of the following sentences is correct?




  1. From now on, the biochemistry lecture classes on Mondays at 10.30 a.m. will be held on Sundays at 11.30 a.m instead.

  2. From now on, the biochemistry lecture classes on Monday at 10.30 a.m. will be held on Sunday at 11.30 a.m instead.

  3. From now on, the biochemistry lecture class on Monday at 10.30 a.m. will be held on Sunday at 11.30 a.m instead.

  4. From now on, the biochemistry lecture class on Mondays at 10.30 a.m. will be held on Sundays at 11.30 a.m instead.





Sunday, April 23, 2017

verbs - help you do (or) to do something - difference


I know that generally native speakers say it usually like this (without the to):



These exercises will help you get better at math.
Can you help me move these boxes outside?



But sometimes, though very rarely, I see it used with the to. Like in this example:



This is just so that you won’t forget that you shouldn’t change these values after you first create them. It’s purely optional, but in the pages ahead you’ll see how useful all-capped constants can be to help you to better read and understand your programs.




I still don't really understand the deference between the two usages and don't know when we should use one over the other. Could you please help me get this straight once and for all?



Answer



As J.R. comments, the presence or absence of to in OP's example has no real significance (the verb is still an "infinitive", regardless of whether it's explicitly "marked" with to or not).


But as this NGram shows, in recent decades the strong trend has been discard that "superfluous" to...



It may be worth noting this ELU answer and this UK corpus NGram suggesting Brits still cling to to, but I suspect the chart reflects too few instances to be truly significant, and that in practice UK usage either does already, or soon will follow the primarily US-led trend.


xna - How does flocking algorithm work?


I read and understand the basic of flocking algorithm. Basically, we need to have 3 behaviors:
1. Cohesion
2. Separation

3. Alignment


From my understanding, it's like a state machine. Every time we do an update (then draw), we check all the constraints on both three behaviors. And each behavior returns a Vector3 which is the "correct" orientation that an object should transform to. So my initial idea was


        /// 
/// Objects stick together
///

///
private Vector3 Cohesion() {
Vector3 result = new Vector3(0.0f, 0.0f, 0.0f);
return result;
}


///
/// Object align
///

///
private Vector3 Align() {
Vector3 result = new Vector3(0.0f, 0.0f, 0.0f);
return result;
}


///
/// Object separates from each others
///

///
private Vector3 Separate() {
Vector3 result = new Vector3(0.0f, 0.0f, 0.0f);
return result;
}

Then I search online for pseudocode but many of them involve velocity and acceleration plus other stuffs. This part confused me. In my game, all objects move at constant speed, and they have one leader. So can anyone share me an idea how to start on implement this flocking algorithm? Also, did I understand it correctly? (I'm using XNA 4.0)




Answer



You really don't want constant velocity. Flocking is going to work and look better if the boids can speed up or slow down while flocking. Otherwise a separated boid may never be able to catch up to the flock.


This article has some very easy to read code (CoffeeScript), a decent explanation, and a pretty demo you can tweak:


http://harry.me/2011/02/17/neat-algorithms---flocking/


word choice - I haven't noticed that vs. I didn't notice that


Which of the two sentences should I use?




A: I haven't noticed that.


B: I didn't notice that.





Reference Time, Coordinating Conjunctions and Past Simple/Perfect Tense


This is an exercise from Face2Face English course with the solution provided in the workbook, but with no reasoning.


In the exercise below I would like to know (actually confirm mine) the Reference Time, and if there is any level of relationship between coordinating conjunctions and the sentence tense. For example, if, under some circumstances, the tense in the sentence before and after "and/but" is the same when there are no other clues such as time expressions.



I finally finished tidying about 3 a.m. and a few minutes later I was/had been fast asleep. I woke up suddenly at 8 a.m. I arranged/had arranged to meet my parents at the airport at 8.30 a.m. but I didn't set/hadn't set the alarm!



To be specific, do you put both arrange and set in the same tense, or one of them in the past perfect and the other in the past simple (the course provides the answers but I want to know why, and know other speakers' opinions (esp. natives) other than the authors - sometimes there is more room for differences and I want to to know that?


-Usually, the arrangement is done before setting the alarm, but do you treat them as indefinite events with no order before the reference time? what is the reference time in the text (this one is not given, but I can think of one)?



Note: I could have written the exercise with just the answers and asked for the reasoning only, but I think it is better not to influence your answers by the author's. I could be wrong, but what I really want is to understand why.



Answer



I finished ... I was fast asleep ... I woke up at 8 a.m. are ordinary narrative past forms in which RT moves forward with succeeding events.


When you hit 8 a.m., however, you find you must allude to events which occurred before RT, your arrangement with your parents and your failure to set the alarm. These two prior events—or this prior event and prior non-event!—give rise to the distressing state in which you found yourself at RT, 8 a.m. Consequently you should employ the past perfect:



I had arranged to meet my parents at the airport at 8:30 a.m. but I hadn't set the alarm!



This does not express any particular chronological sequence in the prior events because it does not 'express' the prior events per se: it alludes to the prior events as causes of your current (i.e. at RT = 8 a.m.) state of having to scramble to make your appointment.


Saturday, April 22, 2017

xna - How to create simple acceleration in a 2D sprite?



So here's what I thought might work but half the time I press the 'Right' key, it results in a crash and the rest of the time seems to produce no acceleration at all.


if (KeyboardState.IsKeyDown(Keys.Right))

while (motion.X < 1)
motion.X += 0.001f + motion.X;


I want to know why exactly it won't work, and any possible alternate algorithms.



Answer



To implement basic acceleration you need to know a little physics. The basics you need to know about are the relationships between:



  • Position - Where your object is

  • Velocity - The direction and rate your object is changing its position

  • Acceleration - The direction and rate your object is changing its velocity


So, to add acceleration, you need to have Position and Velocity already implemented. I'll assume you're doing that already, since you're asking about Acceleration.



Since you have velocity already implemented, I'll assume you have something like:


player.x += player.velocity.x * dt;
player.y += player.velocity.y * dt;

Where dt is the time since the last update. Now if we want to change the velocity with respect to time, we just need to add a line like this:


player.velocity.x += player.acceleration.x * dt;
player.velocity.y += player.acceleration.y * dt;

Now, if we want to modify that acceleration with the keyboard, we can do something simple like:


if (KeyboardState.IsKeyDown(Keys.Right))

player.acceleration.x += .01f;

Friday, April 21, 2017

grammar - Are these Dummy subjects?


Are these Dummy subjects?


It was nice to see him


It's obvious that in this sentence "It" is a dummy subject and the sentence can be reconstructed as "To see him was nice".


But what about this: It is time to watch


Is the case same here as in the first one? Can it be reconstructed to "To watch is time"?


Also wanna ask something additional: We were happy to see each other Now what happens in this sentence? "to see" is something lie a complement to the adjective "happy"?


Some other examples like this one: He is ready to play, She is prepared to play the piano




relative pronouns - Is there any difference between “which” and “that”?


What is the difference between the words which and that?


For example I have the following sentences:



  • “I have a car which is blue.”

  • “I have a car that is blue.”



Are there any rules specifying usage of which and that?



Answer



There is no difference in meaning. There is a difference in use.


Relative clauses—the sort of clause you use, “which is blue” / “that is blue”, which tells us something more about the noun referred to by which or that—are of two sorts: restrictive and nonrestrictive.


A restrictive clause restricts the noun it modifies to what’s defined in the clause. The clause identifies the noun and is essential to your meaning. For instance:



I looked at the books which he sent me last week. … The books I’m talking about are the ones which he sent me last week.



A nonrestrictive clause adds information about the noun it modifies. The clause is almost parenthetical, it could be left out without changing your meaning:




I looked at the books, which he sent me last week. … The books have already been identified in our discourse, I’m just throwing in a by-the-way comment about when I got them.



Note the comma in that sentence: it sets the clause off and ‘marks’ it as something added. Now Which/That



That may only be used at the head of a restrictive clause. It is not used, in any register, with a nonrestrictive clause.


Which may be used at the head of either sort of clause.



You may encounter another rule, which is loudly disputed. About a century ago the Fowler brothers suggested a “division of labour”—using that only at the head of restrictive clauses and which only at the head of nonrestrictive clauses. This proposal made sense to many people, it was picked up by several prestigious grammarians and style guides, and in consequence it’s often cited as a “rule”.


But the fact is, this division has never been generally adopted, and there’s no reason to follow it. I myself don’t follow it; quite the opposite, I employ “which” wherever I can, because I believe that that has entirely too much work to do already and a multiplicity of thats is likely to confuse the reader.


But that’s my choice. You’re free to follow your own rule, as long as you don’t put that at the head of a non-restrictive clause.



Thursday, April 20, 2017

java - Texture will not rotate with gluSphere


I have a gluSphere generated in my display that is rotating, but having a problem with the texture rotating with the sphere as well. So in a nutshell, no matter how the sphere rotates, the texture around the sphere remains in the same position regardless.


How am able to update the texture along with the sphere so that it rotates?


private static Texture testTex;
...


// This method is called in init()
public void sphereTexture(GL2 gl)
{
InputStream iStream = null;

try
{
iStream = getClass().getResourceAsStream("cratepng.png");
TextureData data = TextureIO.newTextureData(iStream, false, null);
testTex = TextureIO.newTexture(data);

testTex.getImageTexCoords();
testTex.setTexParameteri(GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
testTex.setTexParameteri(GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);
iStream.close();
}
catch(IOException e)
{
e.printStackTrace();
System.exit(1);
}

// Set material properties
gl.glEnable(GL2.GL_TEXTURE_GEN_S);
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_REPEAT);
gl.glTexGeni(GL2.GL_S, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NORMAL_MAP);

gl.glEnable(GL2.GL_TEXTURE_GEN_T);
gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_REPEAT);
gl.glTexGeni(GL2.GL_T, GL2.GL_TEXTURE_GEN_MODE, GL2.GL_NORMAL_MAP);

gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);

gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR);

testTex.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S);
testTex.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T);
}

// Draw Sphere (FILL, LINE, POINT) method called in display()
public void draw(GL2 gl, GLU glu)
{


gl.glTranslatef(1f, 0.0f, -20.0f);
gl.glRotatef(angleSphere, 1f, 0.0f, 0.0f); //90

GLUquadric sphere = glu.gluNewQuadric();
glu.gluQuadricDrawStyle(sphere, GLU.GLU_LINE);
glu.gluQuadricTexture(sphere, true);
glu.gluQuadricNormals(sphere, GLU.GLU_SMOOTH);
glu.gluQuadricOrientation(sphere, GLU.GLU_OUTSIDE);

testTex.enable(); // enable texture

testTex.bind(); // bind texture

glu.gluSphere(sphere, radius, slices, stacks);

testTex.disable();
glu.gluDeleteQuadric(sphere);
angleSphere += speed;
//System.out.println(angleSphere);

}


Answer



After posting your glEnables I see that you are enabling sphere mapping with glEnable(GL_TEXTURE_GEN_S) and glEnable(GL_TEXTURE_GEN_T) and generate texture coordinates. You shouldn't need to do this since this is done by glu (see here).


Nonetheless, what looks more suspicious is your use of GL_NORMAL_MAP in the glTexGeni function. In the openGL reference page there is no description of how the texture coordinates are calculated using this parameter. You should either remove these two texture generation blocks or try a different parameter in the glTexGeni i.e. GL_OBJECT_LINEAR.


entity system - What is an appropriate level of granularity for component-based architecture?


I'm working on a game with a component-based architecture. An Entity owns a set of Component instances, each of which has a set of Slot instances with which to store, send, and receive values. Factory functions such as Player produce entities with the required components and slot connections.


I'm trying to determine the best level of granularity for components. For example, right now Position, Velocity, and Acceleration are all separate components, connected in series. Velocity and Acceleration could easily be rewritten into a uniform Delta component, or Position, Velocity, and Acceleration could be combined alongside such components as Friction and Gravity into a monolithic Physics component.


Should a component have the smallest responsibility possible (at the cost of lots of interconnectivity) or should related components be combined into monolithic ones (at the cost of flexibility)? I'm leaning toward the former, but I could use a second opinion.




Answer



There's a line between complete granularity, leading to no code wastage or blob-like state (which is why component architectures are favoured), and usability.


Obviously things may have a Position, but they're not necessarily dynamic (so why have Velocity and Acceleration?). However, something with a Velocity is going to be a moving object, so it makes sense to also have Acceleration grouped.


Are you going to have a case where v and a are going to be needed, but you don't want a physics simulation for them? Similarly, is there going to be a point in Gravity if they're not physics objects?


tl;dr Group what makes sense.


punctuation - Is it okay to write "gale force" without the hyphen?



Northern New South Wales is bracing for more flooding today. Heavy rain and gale force winds are expected to hit the region later this morning. (ABC News)



ABC’s news script has no hyphen between gale and force. Is it okay or does it need to be changed?



Answer



According to most style guides, yes, you need hyphens in compound adjectives.


(Note that this only applies to adjectives that come before the word they modify: in she was old fashioned, it is not necessary, because it comes after; in an old-fashioned woman, it is.)


The general rule is to use hyphens only where they are necessary to prevent ambiguity or where they save readers the embarrassment of having to reread a passage. In practice, not all compound adjectives are problematic without hyphens; however, in this case uniformity trumps other concerns. If compound adjectives are always hyphenated, you have something to rely on as a reader. This is an advantage in itself. Secondly, it is easier for writers if they don't have to think about whether or not the compound is still readable without a hyphen.


I have more or less paraphrased Fowler's perspective here, as in Fowler's Modern English Usage; but I believe most style guides reason along similar lines.



difference - 'of which' in 'to the utmost extent of which' (1906 UK)


Source: p 279, The Family, by Helen Bosanquet, BA in Moral Sciences (First Class; Cambridge)



"If the husband is the head of the Family", she continued, "the wife is the centre.
It is she who is primarily responsible for the care of the children;
to the utmost extent of which the family means will allow,
it is her duty to see they are well cared for, both physically and morally;
and it is generally agreed that this duty can be properly fulfilled only by personal attention.



1. Am I right that which 's antecedent is the care of ... ?



2. I can't pinpoint why, but of which bothers me. It feels redundant.
What would differ if of which were removed? Please explain?


Footnote: I encountered the above on p 28 of 296, Understanding Housing Policy, by B Lund.



Answer



Helen Bosanquet BA in Moral Sciences 1906 was using a verb allow of which peaked around 1700, then fell off, and then enjoyed a little renaissance around 1850. It means 'to allow'.


So the clause could be rewritten:


To the utmost extent which the family means will allow of, it is her duty to to see...


To the utmost extent of which the family means will allow, it is her duty to see...


In contemporary English using allow instead of allow of:


To the utmost extent which the family means will allow, it is her duty to see...



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