Saturday, November 30, 2019

java - Polling vs event driven input


I'm developing a game using polling for the input method. However, now that I'm delving deeper into the game menus and other UI components, I'm finding that I'd probably like to have event driven input. Perhaps even having both, using event driven for the UI and polling for the "world" input. I'm curious on what the best way to go is.


I'm defining polling as: each update loop I check what keys are press, where the mouse is, buttons pressed, then run through them and do actions based on the info collected.


I'm defining event driven as: interrupt based events, when an event happens and interrupt is triggered and a code block is run based on the event.


Do you think it's best to go all event driven, all polling, or is a combination of both acceptable? If you have pros and cons for either please list them. Thanks.


EDIT


The game is Java/OpenGL based, so will be released to Windows/Mac/Linux. The possibility of extending that to mobile devices is low. The game is RTS style, 3rd person 3D.



EDIT 2


I'm still not totally happy with the way I've implemented this, but what I'm moving toward is catching events in my UI and if they're not handled by any of my UI components, I pass the event on to the "World" for picking/selection. Something like:


@Override  
private boolean handleEvent(Event event) {
if(hud.handleEvent(event)) {
return true;
}
return WORLD.handleEvent(event);
}


This way I don't get clicks leaking through the UI to select objects behind buttons and what not.


Currently my camera controls are still based on polling, and that seems to be working for now, but I may update that later on.


I appreciate all the answers, sorry I could only pick one!



Answer



It depends on the requirements of your game and hardware. Most games are usually interested in changes to input state, i.e. user presses the fire key and their weapon starts firing, user releases the fire key and their weapon stops firing, user presses the move key and starts moving, releases the move key and stops moving, etc., so an event-driven input system makes the most sense in those cases since the information is already in a suitable format. Plus on the Windows platform, you already receive events for changes to keyboard and mouse state, so it's often a 1:1 conversion from low-level input events to high-level game events. With polling, you'll often find yourself having to generate such events manually by comparing state between the current and last frame. Basically, "which buttons are pressed now?" tends to be far less useful information than "which buttons have been pressed/released this frame?", and given an initial keyboard/mouse state when you initialize your input subsystem, the former can be inferred from the latter anyway for those cases when you need it.


That being said, on certain platforms you're stuck with polling input at a low-level and there's no way around doing the edge checking yourself. However, I've always achieved the best results using events for all high-level logic since that's naturally how those systems tend to operate.


Question About An Implementation Of Parallax Scrolling In C++/SDL/OpenGL


I been working in a project with a team for a Software Engineering class and we think that using the parallax scrolling will help our game to look really nice but we are not really sure if our idea for implementation it's the correct one, so I hope that someon will give us some guidance about our plan.


First, we have three classes, Level, Tileset, Layer, the first one has two vectors of Layers and Tilesets, so our idea is load all the data from a TMX file of the first level in a vector>, but we only draw the part of the map that it's currently in camera, so inside a cycle we draw every layer, but we're not sure how defined a velocity for each layer so the parallax scrolling works like it supposed.


Thanks for the attention and help.


Good day....


PD: If someone need more information, don't doubt in ask.



Answer



Parallax scrolling is just using a set of layers moving with different speed. each layer can be a tilemap, just a sprite, or anything else. normally the most front layer is a tilemap and you only check collisions and other gameplay features with that layer. just keep in mind parallax scrolling is going to simulate 3d projection using only 2d objects, so objects back in the scene should move with slower speed than those in the front.


to ease your work,, you can keep the character(player) in some fixed position. then give negate of player velocity to your parallax node. I suggest for a parallax node you only change setPosition function, in that function instead of moving parallax node itself, you have to move all it's children, respecting their depth value. for example you can use some code like this one:



void move(float deltaX,float deltaY)
{
for(unsigned i=0;i {
children[i]->move(deltaX / child.depth,deltaY / child.depth);
}
}

all the other functions of the parallax node is same as normal node. you don't need to worry about anything else.


meaning in context - Another way to say "We are not relations."


In the movie Forrest Gump, Lieutenant Dan was asking Gump and Bubba whether they are twin brothers, but Gump said:



"No....we are not relations, Sir."




Is it also correct to say if I say this?



We are not related to each other.



or does it have a different meaning?



Answer



"We are not relations" does sound a little strange to me. But it also comes off as possibly a Southern saying (American South). And it fits since Forrest Gump was raised in Greenbow, Alabama, a southern state.


Looking at the definition of relations




relations
a (1) : a person connected by consanguinity or affinity : relative (2) : a person legally entitled to a share of the property of an intestate
b : relationship by consanguinity or affinity : kinship



we see that "We are not relations" serves to mean that they are not family, not twins. So I don't believe it is a matter of correct or incorrect. It might be more appropriate or familiar to say if you are in certain regions.


Possible alternatives include



  1. We are not related.

  2. We are not relatives.



Including "we are not relations", they all mean "we are not family". I think I would've used 1. I think most people are familiar with these two.


Here is some ngram data on the matter. enter image description here


Friday, November 29, 2019

articles - "we write expressions in infix form" - why not "we write expressions in the infix form"?


From Real World Haskell:




We can immediately start entering expressions, to see what ghci will do with them. Basic arithmetic works similarly to languages like C and Python: we write expressions in infix form, where an operator appears between its operands.



Why is there no the before "infix"? This is quite a definite form of writing expressions. Is it because it is given a definition after a comma (" where an operator appears between its operands")?


Or is it because form with the will change its meaning to "a printed or typed document with blank spaces for insertion of required or requested information"?




P.S. A related question: 'in gas state' vs. 'in the gas state'.


(P.P.S. stashing a memorable usage example for myself: "Alf in pog form")




c# - Unity 5 2D drawing sprites programmatically


How can I draw sprites in Unity 5 programmatically ? I am looking for something similar to spriteBatch.Draw() in XNA. The results I get when I search about it are either outdated http://wiki.unity3d.com/index.php?title=SpriteManager (this was written in 2012), or they are done using the unity interface. All I can find is a Sprite class in UnityEngine.dll. Is this what I need ? How would the drawing work ? I really don't get it.



Answer



Unity does not have this kind of "direct mode" rendering, you won't be calling Draw in any update loops for Unity.


In Unity you need to create a game object, then attach scripts to that game object. Those scripts will control how the object behaves, if and how it's displayed on screen, if it's part of the physics system etc.


To create a new sprite to draw on screen you'll need to create a new game object, then attach the SpriteRenderer script to it and set its sprite.


GameObject go = new GameObject();

SpriteRenderer renderer = go.AddComponent();

renderer.sprite = Resources.Load("Sprites/Player", typeof(Sprite)) as Sprite;

This assumes a directory structure of


-Assets
--Resources
---Sprites
----


For example:


enter image description here


Then you'd had a different script for changing the position, rotation etc, depending how you want it to behave.


The easiest way to accomplish all of this without having to write as much code? Create the game object in the Unity editor first. Once the game object is equipped with the sprite you want and the behavior scripts and all that. Drag and drop it into a resources directory. This creates a prefab. Prefabs are just what they sound like, pre-fabrications. They're complete objects that you can then reference and create on the fly.


You'd create those like:


public void CreateObject(string prefabName) {
GameObject newObject =
GameObject.Instantiate(Resources.Load(prefabName)) as GameObject;
}


This will spawn a clone of the prefab you created before. So, if for example, you'd given your prefab the behavior of moving towards the player and attacking, every time you spawn a new prefab of that type, they will start moving towards the player and attacking. The scripts you only had to write once control all of those game objects.


I think the main difference you're seeing here is the heavy use of components. Which you likely haven't seen in other game engines like XNA. Unity really is a powerful engine, but your frustration comes from trying to use it like other engines, when it's not like other engines. Check out my profile for some training, I added a link for a free trial so you don't have to pay.


xna - Friction in 2D game


I'm developing a 2D platformer, although this question could probably apply to just about any 2D type physics; What is the equation for friction? I have sort of a hacky type of friction set up in my game currently, but I'm not satisfied with it because it doesn't account for all forces being applied to my character outside of whatever forces he's generating himself.



Answer



There's two types of friction, static friction and kinetic friction. Static friction is the friction that needs to be overcome to get something moving from rest. You'll notice when pushing a box across the floor, it can often take more force to get it moving than to keep it moving. Or you'll be applying force and it will jolt forward and you'll have to not push as hard. That jolt forward is the point when static friction is overcome and you're dealing with kinetic friction. Kinetic friction is almost always (always?) less then static friction.


Either way, friction is a force just like acceleration. It's calculated based on the normal force of the objects and coefficent of friction (µ).


enter image description here


This free body diagram shows a few forces.




  • Green: The force of friction.

  • Purple: The force being applied to move the object

  • Blue: Gravity

  • Red: The normal force, will equal gravity if the object is not sinking into the surface below.


So when the force of friction and the force being applied are equal, the object will not accelerate. So if it's stopped, it's not going anywhere and if it's moving it'll continue to move at that speed.


So you're going to want to collect some information to simulate friction.



  • The types of materials, this is needed to get the coefficent of friction (µ).


  • The normal force


Then you can simply calculate the force of friction with the following:


friction = µ • normalForce


When you're summing up your forces you include this force. If you have no other accelerations, then your friction is going to be the only force, and will slow your object down.


Thursday, November 28, 2019

procedural generation - Algorithm for generating a 2d maze



What algorithm have you used in the past to generate a simple 2d maze?



Answer



There are a lot of various ways of making mazes. There's a huge list of them and their descriptions here: http://www.astrolog.org/labyrnth/algrithm.htm


I think I used the one described under "Perfect".


imperative sentences - Use of be+infinitive in different meanings


I know that be + infinitive is used for order, instruction and plan but some of the example sentences are confusing to me they are:






  1. I'm to go now. ( what's the meaning of this sentence ?)




  2. Mr johns was to speak at the meeting last monday. ( if this sentence is about past plan, was the plan fulfilled ? Or what's the meanings of this sentence ?)




  3. You are to be on time.(what kind of meaning this sentence implies?)





  4. Am I to believe what they say ? ( what kind of meaning this sentence conveys ?) Now, if the meaning of those sentences is similar to 'supposed to', why be+infini' is used instead of supposed to' ? Is 'supposed to' is the same as 'should' or what? I'm expecting understandable answer. Thank you in advance.







modal verbs - Using “used to” vs "would" when expressing something done in the past


I understand how the phrase "used to" can describe something that was done in the past:



When I was growing up, my parents used to read to me at bedtime.


My dad used to take the family out for ice cream on Sundays in the summertime.




Although these sound fine in conversation, when I see this construct in writing, I often find the word "used" tripping me up. When I'm proofreading my own work, I find myself expecting "used" to be the past tense of the verb use (meaning, "to wield or to utilize"). In other words, when I initially read the word "used," my brain is expecting the word to be used differently – something like:



When I was growing up, my parents used... (a pair of pliers to open pickle jars).


My dad used... (his old t-shirts to wax the car).



So, I'll sometimes reword the original, to eliminate the "used to":



When I was growing up, my parents would read to me at bedtime.


My dad took the family out for ice cream on Sundays in the summertime.




I realize that the construct is plenty common; when I type "my parents use" into Google – both in a web search, and a book search – I find more instances of:



my parents used [to do something]



than:



my parents used [something].



So, my questions:





  • Is it worthwhile to make such edits? Might others occasionally stumble momentarily as they run across the word used used in that context while reading? (Or maybe that's just me?)




  • Finally, is there a reason why (or a context where):





My brother used to loan money to his friends.




would be considered better than:



My brother would often loan money to his friends.



I'd be especially interested in answers from both native and non-native speakers of English.



Answer



For some reason "used to" seems informal to me. I don't think I'd use it (no pun intended) in an academic essay.


But besides that, I don't see a problem with it. Sure, there's ... not exactly an ambiguity, as once you read the complete sentence the meaning should be clear, but what I guess you could call a momentary ambiguity until the reader finishes the sentence. But you could say that about many words. There are lots of words in English that have multiple meanings depending on context. I'm sure we've all had the experience of seeing a word, getting one meaning in our heads, and then reading a little further and having the jarring realization that that was not the intended meaning, so now we have to go back over the sentence and rethink.


So my vote is: In general, don't worry about it and use if freely. But if you're writing a paragraph where you are saying "used to" in the sense of "did in the past" and also "used to" in the sense of "employed for this purpose", you might want to recast the sentence. Like, I think I would avoid writing, "The hammer that Bob used to use to build ..."



architecture - In lockstep networking game, how to handle sudden lags and disconnection?


I am trying to implement a game similar to "Street Fighter" by using lockstep networking model so that two players can play remotely via Internet.


I have read a lot of articles about lockstep networking method and I can basically implement the turn/frame handling for each step.


My understanding is that if it's now turn 101 and if player A has not received turn 101 action (packet) from player B, player A has to wait.



When this situation happens, player B has to wait too because player A will not send out further actions to player B because he is waiting.


Should the game do anything for this situation? For example, I saw games like Starcraft, sometimes there is a dialog showing up to wait for other players and if the count down goes to 0, players can disconnect this hanging player.


In order to do so, I don't understand how to decide who is lagging and what the proper handling is. Both player A or player B would think the other party is lagging because he does not receive the packet for his current turn. What am I going to show to the user? And if the lagging continues, how to end the game earlier by giving a correct game result (the player who lags should be given a loss and the other player should be given a win)? Just similar to the countdown dialog in Starcraft.


And on the other hand, what if the situation is not lagging but is a disconnection from player B?




Wednesday, November 27, 2019

collision detection - 2D Level design/editing/saving questions



I thought about making a simple 2D Sidescroller game like SuperMario. Then i wondered about how to save, load or create the levels for the game. The first thing i thought of was drawing a simple blocky png which represents the level, an making all the parts where the player can walk a special color (maybe lilac). I would import the level in blocks or tiles so i could check for collision.


so my questions are:
are there better methods for this?
what are the professional methods for this?

should i do this with Tiles and a Map editor based on tiles? (for some reason i dont like this, but i guess if its the best method i would use it)
with a tile based level, how would you realize slopes, and how would you check them for collisions?



Answer



For an 2D MMO we use http://www.mapeditor.org/. We use several layers for background, background decoration, objects on the same level as the players and objects in front of the player. And an additional layer with just one red square to mark collisions.


I am not sure if this appoach or the software works out for an 2D side scroller but it may be worth to have a look at it.


Tuesday, November 26, 2019

meaning - "not very much" vs. "a little"


I'm looking at a chart having quantifiers with verbs in it including a lot / quite a bit / a little / very much. I've seen these a lot but now this chart made me think more and wonder. I understand all but the last two sentences.


Does “it snows a little” mean the same as, more or less as “it doesn't snow very much”?



I've searched and couldn't get a straight answer! There were some arguments concerning the implication of expectation, and apparently has remained unconcluded, but here has nothing to do with expectation at all anyway. Actually they were simply put in a chart, but there is no distinction based on their intensity.



Answer



There may be no quantitative difference between a little and not very much. It's all a matter of perspective. Most commonly (i.e., when not use sarcastically), the first tends to mean that you are encouraged by the amount and the second that you are discouraged.



It snowed a little last night. We might be able to go skiing today.



You want to go skiing and you hope that the amount of snow will be sufficient.



It didn't snow very much last night. I doubt we can go skiing today.




You want to go skiing and you worry that there won't be enough snow for that.


word usage - What is difference between people and peoples?


Would anyone like to comprehensively explain? I am not sure peoples word exist or not. Kindly request to you all please explain about this.



Thanks.



Answer



We use the word "peoples" to talk about groups of specific ethnicities, races, communities, or nations.



Estimates put the total population of indigenous peoples from 220 million to 350 million.



"People" can also be used to talk about the human population in general, or a group of 'persons' usually with some shared link between them. Even if they're from the same ethnicity, if you're only speaking about individuals you would say "people".



The people at the pet centre helped me find a dog.




definite article - Use of 'A' vs. 'The'?


The rule states that:



Use (A) the first time you mention something, and (The) the second time you mention the same thing.




Kindly, consider the following example: (source: English for Starters 9)



((I'm going to tell you about a city called Tripoli, in the north of Lebanon. It is a city with lots of beautiful old houses.))



According to the rule, we should say:



((It is the city with lots of beautiful old houses))



because it is the second time we mention the word (city). Why did we use (a) instead of (the) in this situation?





physics - Calculating collision of polygons


Say I have a multitude of 2D polygons floating about on a plane. These polygons can have any side count and aren't necessarily regular.



Assuming I know absolutely everything about the polygons (area, collision point, location, velocity, rotation, angular velocity... etc) how to I calculate what happens to two polygons after collision?


I.e. what will their resultant velocities and angular velocities be after collision?


enter image description here


If not an exact solution, what resources could help me learn how to accomplish this?



Answer



This is kinematics, which allows us to deal with each kind of motion (rotation, translation) separately.


First of all, let's look at the what the new direction and velocity of the 2 object is going to be. We need the normal of the side the collision happens on to get the direction. Given the normal (yellow), the direction of object A (green object, green vector) and object B (red object, red vector) is (black is the original velocity) (the red object is considered static in this example. To get the dynamic-dynamic collision's result, do the same calculation twice and add the direction vectors together):


enter image description here


Basically you get the new velocity of object B by projecting object A's original velocity on to the negative version of the normal and you get A's new velocity by dividing B's new velocity from A's original velocity. To get the result, as I wrote above, do the same with A being static and add the resulting velocity vectors together.


This should solve the translation problem, now onto rotation.



Every object has angular momentum, even if it doesn't rotate. It can be expressed as


L = m * v * r * sin(theta)

where m is the mass, v is the velocity of the dynamic object (again, if both of them are dynamic, simply do these twice), r is the distance of the center of masses and theta is the angle between the vector pointing from the dynamic body to the static body and the velocity vector. You can simplify this to get an angular velocity:


ω = m * v / (1/3 * M * r * sin(theta))

where M is the mass of the static object. Now take this angular velocity and add it to the current angular velocity of the static object and you're done.


Sources:


angular momentum: https://en.wikipedia.org/wiki/Elastic_collision


angular velocity: https://www.khanacademy.org/science/physics/torque-angular-momentum/torque-tutorial/v/ball-hits-rod-angular-momentum-example



modal verbs - Can we use 'may' instead of 'might' in this case?



Saturday. (Beginning perhaps amended.) I know it is madness to keep this journal but it gives me a strange thrill to do so; and only a loving wife could decipher my microscopic script. Let me state with a sob that today my L. was sun-bathing on the so-called “piazza,” but her mother and some other woman were around all the time. Of course, I might have sat there in the rocker and pretended to read. Playing safe, I kept away, for I was afraid that the horrible, insane, ridiculous and pitiful tremor that palsied me might prevent me from making my entre with any semblance of casualness.
(Lolita, Vladimir Nabokov)



The event time of ‘might prevent’ exists since the time of ‘kept away,’ and so ‘might have prevented’ would not be possible, I think. But, when we shift the reference time of ‘might prevent’ from the past to speech time (the present), we could say ‘may prevent’ instead of ‘might prevent,’ without breaking semantic order. (Of course, though ‘might prevent’ is able to denote present tense, I’m asking for the use of ‘may.) Is it possible or is there some problem?





Monday, November 25, 2019

word choice - "point on the chart" or "point in the chart"?


There is a scatter plot with many points, referred to as "chart".


Which of the following is correct:




Move the cursor over a point in the chart.



or



Move the cursor over a point on the chart.





filesystem - Determining the location of installed/on disk game assets


I've been thinking a lot about the best way to store and load assets in your filesystem. By this I mean where in the file system to store them, and how to retrieve them when loading etc., as opposed to how their stored when the program is actually running. I would imagine that this would be a fairly common question, but I can't seem to find it anywhere else, perhaps because I'm not asking it properly.


So far, I have found two strategies, and I would like to know what other ones there are.




  1. Storing the assets in an absolute path on the system. You may have to get the users home directory if the user doesn't need to be an admit/root to install the game, and other OS dependant stuff would probably need to be done to ensure that the path is actually valid, but it seems like this could work well.





  2. Get the game's location on the system, and assume that assets can be found in an adjacent directory. I don't think there is any OS independent way to do this, but it does seem feasible. This might be nice as it doesn't require the user to install the game, making it all around more portable, but it does seem like it would destroy an OS paradigm where specific portions of the game when in a certain place in the os (say /usr/games, and the executable would go in a different directory).




Both of these ways do seem a bit clunky, so are there any other ways to get the location of your assets? Otherwise, which is used more in games you've worked on? Thank you.



Answer



You're over-engineering this =)


Windows games have two different storage areas:


The first is for static data with the installed program and these files are almost always referenced relative to the application itself, or defined in a file (XML usually) that the program loads when it starts up so there are no hard-coded references. Using the Windows Registry to store paths has fallen out of favor.



The second is for user data like saved games, and there is a standard API for working with that directory. On recent Windows the standard security setting stops a user from saving data to the program area, which is why this is done. On Linux, which I am no expert, I'd assume this directory would be a convention to use /usr/games or something in the /usr directory space.


xna - Generating spherical world from heightmapped terrain


I am using a standard heightmapped procedural terrain in my project. However, I want the terrain to appear spherical when the user zooms out. This is an attempt to simulate the appearance of a spherical planet. Here is my current algorithm:


        //get the direction from the "planet" center to this vert
Vector3 sphereCentertoVertPosition = vert.Position - SphereCenter;
sphereCentertoVertPosition.Normalize();


//our rotation axis is the cross between the direction from this vert to the planet center and the root (center of the terrain) to the planet center
RotationAxis = Vector3.Cross(sphereCentertoVertPosition, sphereCenterToRootPosition);

//the amount we rotate is based on the distance of this vert from the center of the terrain
Vector3 fromCenter = vert.Position - Root.Position;
float amount = (fromCenter.Length() / ((myTextureWidth / Scale) / 2)) * (float)Math.PI;

Quaternion rot = Quaternion.CreateFromAxisAngle(RotationAxis, amount);


Vector3.Transform(ref vert.Position, ref rot, out vert.Position);

My main concern is that the rotation axis is not correct. Theoretically, should it be the cross between the vert-to-planet-center and the terrain-center-to-planet-center?



Answer



Hmm, I'm not so sure about rotating the vertices. Perhaps this is not the answer you're looking for, but I can suggest an alternate method.


I've done something similar with maps in my game. I wrote a shader to wrap terrain into a sphere, but it can easily be done outside the graphics card too. It's as simple as mapping the Cartesian coordinates to spherical coordinates. The code would look something like:


public static Vector3f MapToSphere(Vector3f coords, WorldMap MAP) {
float pi = 3.14159265f;
float thetaDelta = ((2 * pi) / (MAP.XSize - 1));
float phiDelta = ((pi) / (MAP.ZSize - .5f));

float RadiusBase = ((MAP.XSize) / pi / 2f);
float theta = (coords.z * thetaDelta);
float phi = (coords.x * phiDelta);

//Limit the map to half a sphere
if(theta > pi) {theta = theta - (pi);}

if(theta < 0.0) {theta = theta + (pi);}

if (phi > 2*pi) {phi = phi - (2*pi);}


if (phi < 0.0) {phi = phi + (2*pi);}

Vector3f coords2 = new Vector3f();
coords2.x = (float) (((RadiusBase) * Math.sin(theta) * Math.cos(phi)) + MAP.XSize / 2f);
coords2.y = (float) ((RadiusBase) * Math.sin(theta) * Math.sin(phi));
coords2.z = (float) (((RadiusBase) * Math.cos(theta)) + MAP.ZSize / 2f);
return coords2;
}


This maybe "too spherical" for you. If so, you can try padding the edges of your map so that the portion turned into a sphere only represents a portion of the surface of the sphere.


Below is an example of the spherical mapping results.


A "flat" map:


enter image description here


And a spherical world, created by wrapping the vertices into a sphere:


enter image description here


Note that there will be a large amount of distortion at the poles if you don't follow the suggestion above to limit the surface area of the sphere this map is stretched over.


word choice - What causes X or What does cause X?


What causes coral bleaching ?


What does cause coral bleaching ?



What is the difference ?? which is grammatically correct ?


Thank you in advance.



Answer



USE THIS: What causes coral bleaching?
NOT THIS: What does cause coral bleaching?




This is one of the most common errors made by learners. Presumably, it usually happens after learning auxiliary verbs (be, do, have) and the subject-verb-inversion in Yes/No questions.


How can we deal with it?


Here is a good rule of thumb: keep in mind that What and Who questions can ask for the subject or the object of the verb. And it depends on what we ask about.




  • If the What (or Who) question asks for the object of the verb, we invert the subject and the auxiliary verb like we do in Yes/No questions. For example,




"What is this?" "This is a book." -- (a book is the object of the verb is)
"What did you say?" "I said, 'Hello'." -- ('Hello' is the object of the verb said)
"Who will you hire?" "I'll hire John." -- (John is the object of the verb will hire)






  • If the What (or Who) question asks for the subject of the verb (and thus the subject of the sentence, when the sentence is a simple sentence), we DO NOT invert the subject and the auxiliary verb. In other words, we use the normal word order: the same word order as we use in declarative sentences. For example,




"What fell on him?" "A book fell on him." -- (A book is the subject of the the verb fell)
"Who owns this house?" "Jake owns this house." -- (Jake is the subject of the verb owns)






In your sentence, you need What causes coral bleaching?, because you ask for the subject of the verb causes (so an answer could be something like: The rise of sea temperatures causes coral bleaching, where The rise of sea temperatures is the subject of the verb causes).



We don't normally use the other alternative, "What does cause coral bleaching?". (It could be used the same way we could use I do like it.) Avoid using it.


confusable - Is there any good methodology to help remember sound-alike words?


I'm working mostly with non-native English speakers, and I it becomes apparent that sound-alike words often cause confusion, particularly in business emails.


There are too many of these words to make a separate question for each one:



to/too/two, brake/break, sail/sale, for/four/fore, buy/by/bye, hear/here, were/wear/where, pair/pear/peer, weak/week, seem/seam (I have also seen Siam in this context :), tail/tale, and many others.




I'm trying to nail them together by helping my friends and colleagues to learn them quickly and effectively.


I'm looking for an effective didactic method to help my colleagues grasp these words.


More details, if it matters: their native languages are primarily Thai and Chinese; many of them are working from homes, so it is not effective to buy books for each of them or arrange study in a school; most of them are rather familiar with formal and natural sciences, not humanities.



Answer



Why don't you try making limericks or tongue twisters for them? Something like



They were wearing wool when they realised they were not where they should have been.


It seemed that the seam had broken.


He braked slowly trying not to break the precious cargo.



The mouse with the long tail had a very interesting tale to tell.


The salesman was happy to make a new sale, now he could afford the sails on his boat.


A week had passed and he was slowly getting weaker.



Things like this for example and then use them to point out the semantic differences. Also you can use it to help reinforce phrasal verbs.


performance - How to continuously find all entities within a radius efficiently?


I have a very large number of entities (units). On each step, each unit needs to know the positions of all units near it (distance is less then given constant R). All units move continuously. This is in 3D.


On average, there will be 1% of the total unit count near any other given unit with the given constraints.



How can I do this efficiently, without bruteforcing?



Answer



Use one of the common space partitioning algorithms, such as a Quadtree, Octree, BSP tree, or even a simple Grid System. Each has their own pros and cons for each specific scenario. You may read more about them in these books.


Generally (or so I've heard, I'm not too familiar with the reasoning behind this) a Quadtree or Octree is better fit for outdoor environments, while the BSP tree fits indoor scenes better. And the choice between using a Quadtree or an Octree depends on how flat your world is. If there's little variation in the Y axis using an Octree would be wasteful. An Octree is basically a Quadtree with an additional dimension.


Finally, don't disregard the simplicity of the Grid solution. Many people ignore that a simple grid can sometimes be enough (and even more efficient) for their problems, and jump straight to a more complex solution instead.


Using a grid consists simply in dividing the world into evenly spaced regions and storing the entities in the appropriate region of the world. Then, given a position, finding the neighbouring entities would be a matter of iterating over the regions that intersect your radius of search.


Let's say your world ranged from (-1000, -1000) to (1000, 1000) in the XZ plane. You could for instance divide it into a 10x10 grid, like so:


var grid = new List[10, 10];

Then you'd place entities into their appropriate cells in the grid. For instance an entity with XZ (-1000, -1000) would fall on cell (0,0) while an entity with XZ (1000, 1000) would fall on cell (9, 9). Then given a position and a radius in the world, you could determine which cells are intersected by this "circle" and iterate only over those, with a simple double for.



Anyway, research all of the alternatives and pick the one that seems to fit your game better. I admit I'm still not knowledgeable enough on the subject to decide which of the algorithms would be best for you.


Edit Found this on another forum and it might help you with the decision:



Grids work best when the vast majority objects fit within a grid square, and the distribution is fairly homogenous. Conversely, quadtrees work when the objects have variable sizes or are clustered in small areas.



Given your vague description of the problem, I'm leaning against the grid solution too (which is, assuming units are small and fairly homogeneously distributed).


Sunday, November 24, 2019

meaning in context - Difference between "kindly" and "please"


Manager to player





  1. Kindly practice every day







  2. Please practice every day





Teacher to student





  1. Kindly wipe the blackboard







  2. Please wipe the blackboard





Student to teacher






  1. Kindly give me a blank paper






  2. Please give me a blank paper






Sister to brother





  1. Kindly pass the butter






  2. Please pass the butter






Which is correct usage in the above contexts?




grammar - "like to be..." vs. "like being..." (and why?)


What is the difference between the following?



A) She likes to be looked at.


B) She likes being looked at.



Could you please elaborate your explanations? The more detail, the better.



Answer




As @Joe says, in most such contexts there's no discernible difference in meaning. But in some contexts there is a possible distinction between infinitive/gerund (or simple/continuous tense). For example,...



Always tell the truth, but don't always be telling the truth.



...which could be mirrored by something closer to OP's example, such as...



I want you always to tell the truth, but not always to be telling the truth.



In such constructions we're forced to acknowledge that the -ing versions emphasise continuously doing something (in this case, the intended sense is that whenever you do say something it should be true, but sometimes it would be better not to say anything at all).





But in OP's example it would be stretching a point to suggest that the first version means if she happens to be aware that people are looking at her, she likes it, and that the second version carries more the implication that she's only really content when people are looking at her.




It's also worth noting what happens if we substitute a different verb...



1: She wants to be looked at.
2: ?? She wants being looked at.
3: She wants looking at.



...where #2 wouldn't normally be considered grammatically acceptable, and #3 would almost always be interpreted as an idiomatic format meaning [objectively speaking] it would be better if she were looked at. Some people would allow that interpretation for #1, but it would more naturally be seen as equivalent (or at least, extremely similar) to both OP's examples.


grammar - Poroshenko’s role is to reassure... - why the infinitive form?


Source: http://www.pbs.org/wgbh/pages/frontline/foreign-affairs-defense/battle-for-ukraine/what-comes-next-in-ukraine/



He seems to be performing quite well. Poroshenko’s role is to reassure the nationalists that there will be no sell out, while on the other hand making a deal with Russia, which at least to a certain extent will be a sell out. It’s a difficult political balance to keep. Poroshenko also has to be a bullish negotiator with Moscow and know that Moscow does not treat weak positions with respect.




How would the meaning of the sentence change if I left out the to particle like this:



Poroshenko’s role is reassure the nationalists that there will be no sell out, while on the other hand making a deal with Russia, which at least to a certain extent will be a sell out.



Would the meaning still be the same or is there some kind of little nuance that makes a big difference to the sentence if you change the infinitive form to its bare form without the to particle?


And now please take a look at these two sentences:



1: The last thing the 'if' statement does is break the loop when a word is found". How can you explain this usage?


2: The location numbers on the map's eastern edge are 2, 5, and 8. If you divide any of those numbers by 3, you'll get a remainder of 2. So all you need to do is use the modulus operator to check for this, and you can tell whether or not the player is on the very eastern edge of the map.




Are they correct? How do all these three sentences stack up against each other?



Answer




Poroshenko’s role is reassure the nationalists that there will be...



Does not sound okay to me. Maybe, using reassuring works there.


to reassure is a verbal use of the word.



reassure - to say or do something that makes somebody less frightened or worried




Think about a simpler sentence and we understand this...



My role is to play cricket over My role is play cricket!



phrase request - What can I say politely when something bad happens?



I am looking for a short phrase that I can say when something bad happens. For example, when my mouse breaks or my computer is hanging.


I know the expression damn it but I need something more polite.



Answer



As mentioned, darn or dang are the closest approximations of damn, and crap also works, but other common alternatives include:




  • shoot

  • geez

  • man!

  • what the heck! (or hell, but that's closer to cursing)


subject verb agreement - A group of boys is/are




1) A group of boys is playing football.



or



2) A group of boys are playing football.




My teacher told me the first sentence is correct since of boys can be ignored to make:



A group is playing football.



It feels very awkward in my mouth to say boys is.




physics - Lunar lander: How to calc acceleration in each step


I'm trying to make a lunar lander simulator. I'm going to use a simple Euler integration. AFAIK all I've to calculate is the acceleration in each step, and then I should be able to update velocity and position.


I'm following this page: http://www.braeunig.us/apollo/LM-descent.htm


There's a paragraph I don't really understand:



Although most operations are self-explanatory, a brief description of acceleration is warranted. Acceleration is broken down into vertical and horizontal components, where the vertical component is normal to the Moon's surface. The instantaneous vertical and horizontal accelerations of a moving body in reference to this surface are Av=Vh^2/r and Ah=–VhVv/r. To this we add the accelerations resulting from gravity and thrust. Gravity, of course, acts vertically downward. The vertical and horizontal components of thrust are a function of the pitch angle.




The author is making a much more realistic simulation here and because of that he is not assuming the Moon is flat. He comes up with two initial values for each acceleration component:


    Av=Vh^2/r

Ah=–VhVv/r

1- Seems that Av is the centripetal acceleration, but where does the Ah come from?


2- Are those initial values really needed? In my game the Moon is going to be flat. I thought taking into account thrust/mass and gravity would suffice.


Thanks in advance.




Saturday, November 23, 2019

architecture - Elegant way to simulate large amounts of entities within a game world



Assume you have a game in which there are many (many many) entities serving some functions, not all of which are constantly needed or need to be considered in every frame. The concrete problem I am working on in which this issue is present is a detailed simulation of a body including its organs.


In the game each creature has its own body which is separated into smaller parts (torso, legs etc.) and sometimes these parts contain organs, which serve a specific function within the body. Whether or not an organ currently serves a purpose or is active is never actually clear. After all, an animal might have an empty stomach which therefore does not need to digest anything. It would be quite ridiculous to check or simulate every object in each frame and very costly as soon as you have many creatures in the world. So I was thinking about a way to smartly differentiate between objects that need to be updated and those that don't.


What I came up with seems like an at least ok solution. It creates a simple queue/stack (essential is that each element gets removed as soon as it's read; the order is irrelevant) called the "attention stack" where objects that need to be simulated reside. Objects that need attention would simply put themselves onto the stack or are put there by other objects. These objects would probably implement a simple interface with a simulate()-function.


Applied to my previous digestion example this would mean:


The player chooses something to eat (assume it's bread) from the inventory and puts it into the mouth of his character and the mouth is put onto the attention stack. In the next frame the the mouth is taken from the stack and its simulate()-function is called. Since it's a mouth it would be reasonable to simulate chewing here. This could go on for a few frames in which the mouth keeps putting itself onto the stack until it decides the food is ready to be swallowed. In this case the mouth puts the chewed bread into the stomach (I know it doesn't go there directly, but the esophagus is left out for simplification), which is then also put onto the attention-stack. In the next frame the simulation of the digestion-process is started. And so on for the rest of the necessary organs.


A foreseeable problem with this are idling objects. A sleeping animal is a good example of this. It could be done as previously described by keeping the sleeping animal on the stack and checking each time if it needs to wake up, but that seems wasteful since that's the only thing being done. To make idling objects more efficient I was planning to add a sort of schedule which stores jobs to be performed at a specific time. If an animal goes to sleep it would put a job on that schedule which would be scheduled for a certain amount of time after the animal went to sleep. This job would then take care of putting the sleeping animal onto the attention stack again. Now, you could say that a sleeping animal that isn't on the attention stack could miss being attacked by something because its A.I. is not simulated, but this is prevented if the attacking object takes care of putting that animal onto the stack again.


Now, I honestly don't know if this is even close to an elegant solution to this problem due to a lack of experience. Am I close to something usable? How is this usually done or does anybody have any suggestions or better solutions?



Answer



This is exactly the way we solved this problem in Stendhal. In our case there are lots of things that happen periodically, but not every turn: Healing spells, plants growing a little further, corpse degenerating, items on the ground expiring.


We have a turn number that is increased in every turn. And we maintain a map of future turn numbers pointing to a set of objects that need to be notified in that turn.



unity - How do I quantify the curvature of a touch swipe?


I'm implementing a touch controller for my game.


I am attempting to imitate Tiki Taka Soccer's "ball shooting" controls (gameplay video), where the curvature of the player's swipe affects the curve of the shot's trajectory.


Tiki Taka Soccer ball shooting swipe mechanic


Basically, I want to move the object to where the user raised their finger, but also apply a curve to the movement, corresponding to the curve of the swipe.



How can I do this?




I'm using Unity 5, and I'll be using the Lean Touch plugin from the asset store to capture swipes.



Answer



Detecting swipe curvature


Treat the finger swipe as a polyline. Approximate its curvature, and use that as a multiplier for how much to “curl” the resulting shot either left or right.


Let's say a swipe path has no curvature if it goes linearly from the start (the circle), to the end, or curvature value 0.


no curvature


I'll emphasise other swipes' differences to this baseline with blue and red colours.


One that makes a 90° right turn has a maximum right curvature, or curvature value 1.



maximum right curvature


One that makes a 90° left turn has a maximum left curvature, or curvature value -1.


maximum left curvature


We can hence find any intermediate curvature by calculating the proportion of the area it covers on either side of the baseline path, as a proportion of that maximum!


-0.90 -0.65 -0.15 0.22 0.68


When the line curves partially to either side, just add the signed areas to get the overall curvature.


wobbly -0.08 wobbly 0.42


Of course, you might still get particularly insane swipes that make a really far-out turn, tighter than 90°.


curvature over 1


It's up to you how you handle these. Maybe you want to clamp them to the [-1, 1] range to prevent people from doing a Fire Tornado Spin Kick—but then again, maybe that would be fun!



Applying curvature to object motion


forces and impulses to apply to ball


To apply a curve to an object's forward motion, apply an impulse in its intended direction (the red arrow to the right; to create the forward motion), then an impulse perpendicular to it (the red arrow upward; to push it "outward"), then apply a constant force perpendicular to it in the other direction (the green arrow downward; to pull it "in" again). For a motion curve in the other direction, just flip the perpendicular impulse and force directions.


You can find the perpendicular of a 2D vector by exchanging its x and y components and negating one of them. Here, you probably want to normalise the perpendicular vectors and multiply them by the curvature value.


Tweak the strength of the forces and impulses to get the effect you want.


Friday, November 22, 2019

hendiadys - "Try and" versus "Try to"?





Try and hit me!


Try to hit me!



Do the above example mean exactly the same and it's just a matter of preference to use which word?



He tried to make it better.


He tried and made it better.




The second example sounds strange when it comes to more formal sentence of that sort. Is it still a correct use of the phase?



Answer



The idiom "Try and X" is a bold command or challenge. This is colloquial, very informal, and does not sound professional. It can sound child-like or naive.


"Try and hit me!" is an idiomatic expression that means "Try to hit me!" or perhaps more accurately, "I dare you to try to hit me. You cannot!" It can be said playfully or antagonistically.


He tried to make it better. This means that he attempted (tried; put forth effort) to make it better. It doesn't indicate whether or not his attempt succeeded.


He tried and made it better. This is a standard conjunction. It means that he attempted (tried; put forth effort), and did in fact make it better. Note that this is not the "try and" idiom; it is not a command.


I will try and make it better. This is an awkward form. It's not the typical idiomatic "challenge" command form. It would surely be understood as I will to make it better. but it sounds a bit "off".


I will try to make it better. This sounds natural, sincere, and professional.


An overbearing boss might say, "I need you to rework this. But this time, try and get it right, ok?" Note the idiomatic use of the command/challenge form. It's a condescending tone.


meaning - What’s a word for how parents treat their kids?


If there were two parents that treat their kids badly, no one would comment,



The Johnsons' behaviour toward their children is bad.




What can replace the word behaviour? Treatment (as mentioned in the comments, it sounds like they are doctors)? I don't really want to use



The Johnsons were treating their children badly.



Because it doesn't fit the essay I am writing.


The psychologists discussed the Johnsons' ______ toward their children.


What would be the appropriate word? Any help would be appreciated.



Answer



(Native American English speaker here.)



Actually, I think "behavior" might be OK, but here are the first two alternatives that came to mind:



The psychologists discussed how the Johnsons are raising their children.


The psychologists discussed how the Johnsons parent their children.



Yes, "parent" can be used as a verb.


If you really, really want a noun, and if you're not happy with "raising of" or "parenting of", here's what I got from a trip to Roget's Thesaurus:



The psychologists discussed the Johnsons' conduct toward their children.


The psychologists discussed the Johnsons' methods of child-rearing.



*The psychologists discussed the Johnsons' parentage of their children. [The meaning here is wrong, but I'm listing it for a reason I'll explain below.]


The psychologists discussed the Johnsons' influence on their children.


The psychologists discussed the Johnsons' effect on their children.


The psychologists discussed the Johnsons' management of their children.


The psychologists discussed the Johnsons' guardianship of their children.


The psychologists discussed the Johnsons' handling of their children.



Here's a phrasal verb, which can make only a clumsy noun:



The psychologists discussed how the Johnsons are bringing up their children.




These might be just what you're looking for:



The psychologists discussed how the Johnsons care for their children.


The psychologists discussed the Johnsons' care of their children.



Time to buy a thesaurus?


Since you now have quite a strong command of the English language, it might be time to buy a good thesaurus. Keeping a thesaurus in book form next to your computer can be wonderfully helpful. Unlike web sites, a book has no advertisements or flashing blinky-bloos to distract you.


Some people don't like Roget's original design for a thesaurus, which is organized by concept rather than alphabetically. However, it has its advantages. It places all the words and terminology for one concept in one article, and related concepts in nearby articles. For example, I found "parentage" in the (alphabetical) index, which pointed to an article listing a couple hundred words for reproduction. On the next page was an article listing a hundred or so words for ancestry, and then words for posterity, and then…"influence". Roget's thesaurus lets you wander around, sometimes fruitfully, sometimes leading you to unexpected surprises. "Care" turned up as a synonym of "treatment". Some web sites try to let you follow related concepts in a way that can't be done with paper, but the current batch tend to be big on animation and light on words.


Another good book to have is a dictionary of synonyms. Unlike a thesaurus, which is designed to help you search for a word when you already know the meaning you have in mind, a dictionary of synonyms explains the differences between synonymous words.



grammatical number - What is the plural of "brother", "brothers" or "brethren"?


In English books, I read that the plural of brother was given as brethren, but I hear people in movies or serials using brothers.


Which one is correct?


Is it the difference due to difference in American and British English?



Answer



Use brothers in both speech and writing.



Brethren is a very old plural which is no longer in use, except in very narrow contexts: in works of fiction which depict historical times, or try to create a similar 'atmosphere'; in religious (or quasi-religious) works which embrace the language of the King James Bible; and in works which allude to uses of this sort, either mockingly or affectionately.


game mechanics - How to make a scrolling background


I'm making a Shooter game like "1943" and "Jamestown". I am Using Visual Basic 2010. I was wondering how I would make the background scroll up to simulate moving forward. I would also like it to scroll slightly to the left and right when the player reaches the sides of the screen. Finally, how would I make this efficient? I was thinking about using a animated GIF or making a looping BitMap. Please could someone help me out?



Answer



The backgrounds in Jamestown are not looping bitmaps, because they are always changing from the start of the level to the end.



But if you only need a looping bitmap, and you only need it to loop vertically, the easiest way I know is the following (cross reference with the image below):



  1. Draw the background twice, stacked vertically like on the image below. Of course the image you use must be seamlessly tileable. The red rectangle represents your screen.

  2. Start moving both background instances down. You do this by adding some value to their vertical position each frame.

  3. When they reach the position represented in the image (e.g. when topBackground.Y >= 0), subtract one background height from each of their vertical positions to bring them back to step 1.


  4. Repeat.


    enter image description here





There are more complex ways of handling the problem depending on whether you need to loop horizontally and vertically at the same time, or if you need to zoom and rotate the background. You can use these as reference if needed, although I'm not sure how you'd translate it to your platform:



networking - Best strategy (tried and tested) for using Box2D in a real-time multiplayer game?



I am currently tackling real-time multiplayer physics updates for a game engine I am writing. My question is how best to use Box2D for networked physics. If I run the simulation on the server, should I send position, velocity etc to every client on every tick? Should I send it every few ticks? Maybe there is another way that I am missing?


How has this problem been solved using Box2D before? Anyone with some ideas would be greatly appreciated!




grammar - Is the use of "one of the" correct in the following context?


I want to know what the constraints are on using the phrase one of the.


Is it used correctly in this example?



He is one of the soldiers who fight for their country.






Thursday, November 21, 2019

grammar - Can we use "to be stripped" instead of "being stripped" in this sentence?


The warning from the European commission could lead to that country being stripped of its European rights.


(As far as l know we must use infinitive after nouns )




java - How would I implement a realistic stock market?


I'm making a corporation simulator, and it contains stocks. In the game you can buy and sell stocks, but I can't implement a realistic change in the price for them. How do I make them change up/down in a realistic way?



Answer



Rather unspecific to the programming language or the platform mentioned, but I would probably go for a greater change as a primary depiction of important stock change, and then generate a small fast change upon that to depict the hooky part of the stock graphs.



So basically:



  1. You start at time T1. You're going towards time T2. Price at time T1 is P1. P2 is end price.

  2. You generate a random number (probably based on some events, maybe?) for P2. This is your larger number target price.


  3. You iterate towards it with a timestep. If you update a couple of times (denoted as Tt) between those timesteps, you do



    (T2 - T1)/Tt = Your time step






  4. To get the price at this time, you do



    P1 + (P2 - P1)/Tt * AmountOfTimeStepsPassed





  5. This will get you a pretty straight line, so you could look into something like Bezier or something to make a curve. But to get those hooks, you need to add a very small totally random deviation upon it. This needs to go from a small negative number to a small positive number!



    P1 + (P2 - P1)/Tt * AmountsOfTimeStepsPassed + SmallRandomNumber






The smoother line would represent the great change, and the less smoother line is the actual stock.


The articles "a" and "the" in generic statements


This is intended as a generic statement:



*A madrigal is popular.




This means that being popular is a requirement for being a madrigal.


...of course this conclusion is wrong, so I've marked the example with a star.



*A tiger is in danger of becoming extinct.


The tiger is in danger of becoming extinct.


Tigers are in danger of becoming extinct.


The Indefinite Generic a tiger is ungrammatical with the predicate become extinct, because that extinction can only happen to a species, and it means that every member is dead. In contrast, we we can use the Definite Generic because the predicate is characteristic of the species. We can also use a Plural Generic because we're speaking of tigers in aggregate.



I read those examples and explanations in a grammar book (or, more likely, online). Would anyone please explain those in a more simple way, so that I could get it? I cannot tell what the explanations mean very well.



Or could you possibly explain that with another example that is easier to understand?



Answer



I have considered that you have gone through this document here, the original source of this question and the other answer here, but then it's still perplexing.


So now...


I shall try to address the Or could you possibly explain that with another example that is easier to understand? part here:


Articles are difficult to understand and depending on the context their usage changes. I have recently asked a question on this.


Now, please note that I'm creating the context here.


The scene is — you are standing in the Sasan Gir Forest (home to the Asiatic Lions) and I'm with you providing some information about the area and the animals found in. I'll use all those three sentence structures in concern.






This means there is a (one) lion somewhere who is friendly.



What that explanation says -- "the extinction happens to every member of that species." Correct! Compare it with this example. Any one tiger cannot be in danger to become extinct. And yes, species is a group noun and can take indefinite article. OALD example says -"a rare species of beetle."



Now,





This in this context means I'm talking about the specific lions, precisely I'm talking about the Asiatic Lions who are friendly and not the African lions.




What that explanation says --"the predicate is the characteristics of the species." True again! However, in my example, I'm not talking about extinction but friendliness and hence, it could be understood that I refer to the character of friendliness of particular lions. When we are talking about extinction, we should expect this to be true of any tiger because when the species of some animal gets extincted, you don't find that animal anymore.



And finally,





This takes the entire species of this animal. It talks about the characteristic of an animal. As we say dogs are loyal, which means take any dog, it's loyal because it's it character.



What that explanation says -- "we are talking about the tigers in aggregate." Correct! This matches with the example given above #3. Without any article, it means you are talking about the entire mass, species as a whole. Check - dogs are loyal to humans.






All in all, the plural generic seems to be easily understandable for English learners like me.
This site confirms it! :)


Wednesday, November 20, 2019

prepositions - By + gerund, or gerund only




I managed to win using this technique.
I managed to win by using this technique.



Which is correct? And why?



Answer



Both are grammatically correct depending on your intended meaning. Your first sentence says "I won while I was using this technique" and the second says "this technique was the reason I won."


Take the following examples:



I managed to win with one hand tied behind my back.




This sentence says "I won in spite of having one hand tied behind my back".



I managed to win by tying one hand behind my back.



This one implies that tying one hand behind your back actually was the reason for winning.


So, essentially, it comes down to what you are trying to say. Using "by" emphasizes that it was the reason for winning.


Generically, "by" shows how something was done. If you omit it, you are just stating that it was done.



collision detection - How do I make A* agents avoid other agents?


I'm implementing a multi agent A* algorithm on a tile map. Agents move only in the X and Y axes. I avoid collisions between them by checking where the others are when calculating paths.


It works fine except the situation where agents have to pass the same tile from different directions. In situations like this, an optimal solution would be for one agent to wait for the other to pass:


Sample situation


Also, if there's no northern corridor, then pathfinding fails.


How could I implement such an algorithm?



Answer



You can start by letting the pathfinding fail. On failure, choose a random time in the future to re-try pathfinding. Some low level networking protocols work that way, and quite well. What you have to do is build paths one at a time, and mark as used all the tiles an agent will pass through. When further paths fail the random timer to restart will help spread out the new path searches and break up looping failures.


The second part of your problem could be handled by returning two paths. The first path is the regular return, even if it fails from a block. The second path is a path that completely ignores all the agents. You can then use the knowledge gained from these two paths to decide whether waiting or taking the long way would be better. The heuristic for that decision will take some work, but it's better than not trying anything at all.



In the very bad case where your agents are getting blocked a lot by single width corridors like this you may have to add safe spots to stand where agents can quickly path to and wait for their real path to open up (so the agent doesn't just wait and block a corridor).


graph - Why is the origin in computer graphics coordinates at the top left?


From what I've seen almost all things use coordinates where (0, 0) is at the top left and the positive Y-axis goes in the downwards direction of your screen.


Why is it like this? Why not the conventional positive Y-axis going upwards like shown in graphs in simple math classes?



Answer



This is caused in the history. Early computers had Cathode Ray Tubes (CRTs) which "draw" the image with a cathode ray from the upper left corner to the lower right.


To ease the interface between the graphics card memory and the CRT the memory was read from the beginning and the image was drawn from the top left (with the lowest memory address) to the lower right (with the highest memory address).


Extension (based on the comments)


The CRTs are based on analog TV sets that were available at that time.


The TV sets create the image line by line first from left to right and then from top to bottom. The reason for this can only be assumed to be based on the writing style in western contries.



Tuesday, November 19, 2019

camera - Creating my own kill cam


I plan on creating my own kill cam system for a sandbox tool set. After thinking about the mechanics of the kill cam itself, however, I'm quite lost. I'm trying to recreate the ones commonly seen in call of duty games that show, from the view of the killer, the actual killing scene.


My Thoughts:


-I can't just keep in memory when people kill others because I wouldn't know when to start the 'recording process'. There is on way for me to accurately determine when somebody is 'about' to kill someone.


-My only real idea so far is to have a complete duplicate of everything loaded off to the side copying all the movement from the original world but with a 10 second delay. That way, all the kill cams would be 10 seconds long and the persons camera would just be moved to the second world of their killer.



My Questions:


Is there already an accepted way to do this? Does anybody have any good ideas for something like this? Thanks if you can!



Answer



Store the last few seconds of movement data of relevant dynamic objects.


This data should be complete enough that it can be used to reconstruct a killcam scene if necessary, but incomplete enough that you can afford retrieving and storing at short enough intervals.


Examples of things you may want to track:



  • Which way a visible player is moving/looking

  • Whether killer is zoomed in on gun scope



Things you probably want to optimise out:



  • Data about players whom the killer cannot see

  • Anyone's actual screen output


prepositions - Paraphrase "Dusk closed across the house, sweeping its long shadows over the plain"



Dusk closed across the house, sweeping its long shadows over the plain, the horizon merging into the sky.



I cannot conceive what it looks like.



Are close and sweep used figuratively here? And are across and over used interchangeably here?



Answer




Dusk closed across the house, sweeping its long shadows over the plain, the horizon merging into the sky.


Are close and sweep used figuratively here?



No, close and sweep are not used figuratively. Rather Dusk has been personified and given the ability to "do" things, such as "close" and "sweep."



And are across and over used interchangeably here?




I am not sure what you are asking.


You can switch "across" and "over" in the sentence and have the same basic meaning.



I cannot conceive what it looks like.



This is meant to be a desciption of the darkening of the land and sky at "dusk." Dusk is the latter part of twilight. Twilight is the time after the sun goes down. (So first the sun sets, then you have twilight, then you have dusk, then you have nighttime. Except that they fade into each other.)


In this sense, dusk is the closing of the day, just as dawn is the opening of the day.


In this case, the scene apparently intends to describe the increasing darkness that dusk brings.


You could paraphrase it like this:


There was a house on a plain. After the sun set, the sky got darker and darker until I could barely see because it was dusk. Then dusk said goodbye to the day and went over the house and across the plain with its shadows, and the sky became so dark that even the horizon disappeared.



Note "shadows" is in the plural. The intent of the author seems to be that "shadows" (plural) refer to the darkness that dusk is and brings/sweeps, and not to the house's shadow (as cast by the setting sun). Ordinarily, the setting sun would bring long shadows, but here it is Dusk that brings its shadows and sweeps them over the plain. Shadows are the darkness that dusk brings with itself.


Creating custom collision map for 2D


I have a 2D level that I have built in my map editor, and I was wondering the best way to create a collision map for it.


I have a collision map layer in my map editor, which saves each node (for example, a rectangle would be just 0,0 0,50 50,60 0,60)


I was just wondering how I could take my node locations and convert it to a collision map for Unity.



Thanks! I feel this has to be able to be done, I can think of how I would do it in flash... but I am not sure how to manipulate it in Unity.


EDIT PICTURE: So I have a node at each one of these red dots (surrounding my terrain lets say) I want to build a collider from those nodes


nodes collision map



Answer



I thought since these types of questions seem to show up now and then I'd explain myself a bit more in detail.


Assuming you have a 2D level from a heightmap like in the image without any "overhanging" geometry:


What we want to do is check if point p is below the line, in which case we have a collision at l_p. To accomplish this we interpolate v1.Y and v2.Y value to check the height of the line at p.X. If this l_p.Y is larger than p.Y then there is a collision.



  • Start by checking if v1.X <= p.X < v2.X

  • calculate interpolation amount (a), ie, how large part of v1.Y and v2.Y respectively should be used where a = (p.X - v1.X) / (v2.X - v1.X)


  • calculate interpolated Y by y = (1-a) * v1.Y + a * v2.Y

  • if y >= p.Y then there is a collision

  • If needed solve interpenetration by setting p.Y = y

  • IMPORTANT: If you apply an impulse to the body at this point make sure to check that there is actually a closing velocity ie that there is a velocity pointing downwards in this case. Otherwise you might get another collision reported next frame sending the body downwards again.


check if point p is below the line v1-v2


questions - I wondered what are your plans? & I wondered what your plans are



Are Both


"I wondered what are your plans?"


&


I wondered what your plans are."


Correct?


There is a little difference in the the existence of quotation mark.




Answer



Yes, they do mean the same with the caveat that the first example



I wondered what are your plans?



Would normally require a comma



I wondered, what are your plans?



or a swap to




I wondered what were your plans (eg for the weekend)?



Monday, November 18, 2019

word choice - Using "lesser" or "smaller" in reference to an abstract quality


In Italian "piccolo" (small) has two comparative forms: "più piccolo" and "minore". While "più piccolo" can be used to refer either to physical size or age difference, "minore" generally refers to age difference or to an abstract quality, rather than physical size.


So, Italians can correctly say:






  1. Our room is "più piccola" than yours.




  2. The incident is of "minore" importance.





It is clear to me that in "1" case the correct English word to replace "più piccola" is "smaller", but I'm not sure whether in "2" case one should replace "minore" with "smaller" or with "lesser", or if both are correct.



Can anybody explain if there exist a parallelism between Italian and English in the sense above and if "smaller" and "lesser" are both correct in "2" case?




grammar - Usage of "would" and "will"


What is the difference between would and will in the following examples?





  1. How would you use this word in a sentence?

  2. How will you use this word in a sentence?





the usage of 'so' in ' it does so very slowly''



The moon rotates itself but it does so very slowly.



In this sentence, I wanted to know the usage of so. So means 'very' or 'rotates itself'?




How to implement turn-based game engine?


Let's imagine game like Heroes of Might and Magic, or Master of Orion, or your turn-based game of choice. What is the game logic behind making next turn? Are there any materials or books to read about the topic? To be specific, let's imagine game loop:


void eventsHandler(); //something that responds to input

void gameLogic(); //something that decides whats going to be output on the screen
void render(); //this function outputs stuff on screen

All those are getting called say 60 times a second. But how turn-based enters here? I might imagine that in gameLogic() there is a function like endTurn() that happens when a player clicks that button, but how do I handle it all? Need insights.



Answer



A turn based game is going to be governed by a state machine. Basically, you would lay out a series of states that can occur in a logical order.


At a high level, a player's turn could be the start of a new state, followed by all the possible actions that are allowed during that turn.


For instance



  • State - change player


    • it is now player 1's turn



  • Actions allowed

    • attack

      • select enemy to attack




    • defend

      • select unit to defend



    • move unit

      • select unit to move

      • check to ensure movement is allowed




    • etc




Obviously this will balloon quite quickly, as I've only sketched out an extremely limited plan. Having a good grasp on possible states early on will mean that you should be in a good position to implement. I'd highly stress sketching out exactly how you want the game to run....a good turn-based game requires a lot of planning IMO.


Sunday, November 17, 2019

mathematics - How can I move an object in an "infinity" or "figure 8" trajectory?


When I want to move object around point I do:



    point.x *= cosf(timer.timeElapsed);
point.y *= sinf(timer.timeElapsed);

How to make point move on eight or infinity sign trajectory?



Answer




Some possibilities:


Lemniscate of Bernoulli


Lemniscate of Gerono


Lemniscate of Booth


Watt's curve



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