Wednesday, May 31, 2017

java - How do I avoid floating point indeterminism when implementing lockstep?


I am working on a multiplayer RTS game in Java. It uses lockstep for networking, which requires that both computers can deterministically.


These are the 2 closest/more viable approaches I could come up with- but both have issues:




  • The first is to just use int and long for all my player positions and stuff, and get any use of floating point math totally out of the game model. I like this concept- but the problem is what happens when I need a square root, or a cosine? I would have to basically make an entire math library!





  • I also found that I can use the strictfp modifier and StrictMath class to do deterministic math with doubles... Which I could see using this to create deterministic math within my games model. It would be very prone to bugs as it would be very easy to accidentally go outside of the "strict" scope though.




Also I cant seem to figure out if serializing a float or double causes it to lose its determinism. I'm using Kryo/Kryonet right now, but I cant seem to find any information on if it is deterministic with floats or not (I cant seem to find any information on the built in java serialization either, or any other serialization library)


Does anyone have any suggestions on how I could tackle this problem?




grammar - How to use "when" correctly as a conjunction


Is this sentence correct?



When I will go, I will talk to you.



I mean to ask whether or not we use will with when in this kind of sentence.




Tuesday, May 30, 2017

What is the possessive of Saint John's?


We have a city here in Canada named Saint John's. It is always spelt that way; the 's is part of the name (this must be a very unusual case, I'm not sure).


What would be the correct way to refer to something the belongs to it? 'Saint John's' mayor', 'Saint John's's mayor', or ... ?




past simple - Question format using did


Is there any meaning difference in below questions?



a) Which movie you saw yesterday?


b) Which movie did you see yesterday?




ambiguity - gave them each a phone and a computer


a. I gave a phone and a computer to my two best students.


b. I gave them a phone and a computer.


c. I gave a phone and a computer to both of them.


d. I gave them both a phone and a computer.


Can we tell if



  1. I gave them each a book and a notebook



or



  1. I gave one a book and the other one a notebook


?


Many thanks




3d - How to get translation from view matrix


How can I retrieve the camera's world-space position from its view matrix? The only answers I've seen to this question suggest the translation is in the last row/col but this wouldn't work since the matrix contains [x (dot) right, y (dot) up, z (dot) look]




algorithm - Convert 2d generated level to graph or analyze


Do you have any idea how to extract graph data from this type of procedurally generated level?


enter image description here



Well, actually we need to analyze only top level (gray). Background (black) does not matter. What I am looking for is a way to statistically analyze such type of generated maps. For example how much isolated areas I have (it's not hard, I know), how much branches in each area I have and which areas has exit.


Do you remember any algorithm or math instrument to do that? Memory does not matter, algorithm complexity does not matter too. It's not runtime task.


P.S. A desired result can look like this:


enter image description here



Answer



Here's something you can try. First, take a map like this:


map


Record the distance from the edge distance of each empty cell. You can do this iteratively using cellular automation. I've used Manhattan distance but you can use others, although I think your choice affects a few of the following steps.


distances


Find the cells that are more distant than all their neighbours, a.k.a. local maxima. Mark these as peaks peak.



peaks


Find all the cells that are at least as distant as all their neighbours. I guess you can call these ranges range; they form groups that are local maxima for the most part.


ranges


From here you can connect most of the ranges range to peaks peak or other ranges range by looking at their neighbours and hill climbing; these will form ridges ridge.


ridges


You might notice that not everything is connected, particularly on the right part at some narrow passageways. You can connect them up by finding such passageways and hill climbing away from them; eventually you'll reach a range or peak. Here's one way to identify these: find cells that are:



  • neighbours

  • have minimum distance from the edge

  • have opposing directions of ascension



For example, given this group of four cells:


group4


The top-left cell can ascend to the left, and the top-right cell can ascend to the right and bottom. Since left and right are opposites, those two cells form what you might call a col col. Similarly the top-left and bottom-left cells are also opposites and part of a col. Just like with the ranges, you can hill climb ridge to connect the cols to the rest of the graph (if they weren't already).


cols


That's it; you should have connected graphs for each contiguous area. You can convert the peaks peak, ranges range and cols col into nodes, and the connecting ridges ridge into edges, for graph analysis.


graph


You also have some metadata to play around with; the distances of the peaks and ranges represent how wide those areas are, and cols tend to be choke points.


I'm not familiar with the various Computer Vision algorithms for finding topological skeletons (like straight skeleton or medial axis), but the general idea seems to be the same.


optimization - Does it matter who does the collision detection?


I gave an answer to How to decide which GameObject should handle the collision?, and received a lot of negative feedback on it, claiming that it does not matter who does the collision detection. I am not understanding that stance.


For example:


There are 100 bullets and 1 player on the screen. Let's assume brute force collision detection and no optimization such as layers or references.


If the collision detection is done by the bullet, each bullet must detect for collision on 100 different objects. That's 100 x 100 detections, for 10000 detections total.


If the player does the detection, that's 100 detections total, one for each bullet.



Am I mistaken? If so, what am I missing?



Answer



It does not matter in general.


Your examples aren't exactly fair. Your "player does collision" check looks like this:


for each player:
for each bullet:
if player.intersects(bullet), report it

Your "bullet does collision" check looks like this:


for each bullet:

for each other object in the world:
if bullet.intersects(object), report it

Yes, in that case, the first example is definitely better. It will execute 100 times, whereas the second example executes 10,000 times. A more fair example would be for each bullet, for each player for the second case, which will also loop 100 times. If the first example is allowed to take advantage of the fact that system has individual lists of types and that bullets don't need to test against other bullets, why is the second not?


Most general-purpose collision systems don't operate like that because they don't have the foreknowledge of the system required by your first example, and because to build it out could be expensive in terms of memory, and not always a computational win. Doing so means you need to store collision properties in separate arrays for each type of object that can interact, or otherwise similarly manage and configure different blocks of collision data and iterate them possibly several times at different times in the update loop and it can quickly become a cumbersome and potentially cache-unfriendly mess. There are scenarios where such a specialized collision handling structure could be advantageous over other methods. But they are specialized scenarios.


In general collision handling works by looking at N objects and (modulo various optimizations for spatial organization, preventing duplicate checks in a given frame, et cetera), tests them all against each other, blindly firing out notifications to any interested party that "these two things hit each other, do something about it if you want."


Monday, May 29, 2017

modal verbs - Help pinpoint the usage of 'could' in these examples





  1. whether a sentence is truth-neutral or truth-committed often depends on factors other than the choice of verbal construction. In I’m surprised that your wife should object, the effect of the main verb is to cancel out the neutrality of the should + Infinitive construction, with the result that we clearly understand from this sentence that the wife does object. There is hence no logical difference, in many cases, between should + Infinitive and the simple Indicative form objects. This is not to say, however, that there is no difference in feeling. In I’m surprised that your wife should object, it is the ‘very idea of it’ that surprises me; in I’m surprised that your wife objects, I am surprised by the objection itself, which I take to be a known ‘fact’.
    The meaning swings in the opposite direction (from truth-commitment to truth-neutrality) through the influence of verbs such as believe and suppose:
    I believe (that) his mother is dead. | I suppose (that) you’re waiting for my autograph
    Because of the essential element of uncertainty in the meanings of these verbs, a that-clause that would elsewhere be truth-committed becomes truth-neutral. The same applies to adjectives such as possible and likely.

    We could go on to note that the primary modals (e.g. can, may, will) also express an element of uncertainty, and so belong to the truth-neutral category. However, they express more specific meanings, such as ‘possibility’ and ‘obligation’, whereas the forms with ‘theoretical’ meaning discussed here – the Infinitive, the Subjunctive and ‘putative’ should – express truth-neutrality in its most generalised form.




  2. The difference between ‘arrangement’ and ‘intention’ is a very slight one; so be going to + Infinitive could be substituted for the Present Progressive in all these examples.



  3. Be going to implies that the conditions for the future event already exist. However, will could replace be going to in these two examples with little difference of meaning.

  4. Without an adverbial, a time in the near future rather than remoter future is generally intended: one could insert the adverb just or soon in these sentences to make the imminence explicit.


-- Leech, Geoffrey N. 2004. Meaning and the English Verb. Harlow, England: Pearson/Longman.




Do they indicate conditional (hypothetical) possiblities or factual possiblities in these examples?


I have come across them a lot in this book as well as in ELL answers. From my understanding, may or can is used a lot in such context of giving useful information.


I wonder if the preterite form makes these statements more tentative or informal or what.



Answer



Per my comments, it's really just a stylistic choice to use "preterite" (past tense) could rather than present tense can in all 4 examples. It doesn't significantly affect any "tentative/ forceful" nuances.


In the first example, could is a largely redundant stylistic usage. It's a bit dated/formal/academic (I might almost say pompous). The normal meaning (possibility) doesn't really apply here; it's not that the authors could/might go on to note [blah blah] - the very sentence that tells us they could do that really does do it!


The other three usages just express the standard possible, optional, alternative sense. In every case, it's a matter of You could do A, or you could do B (where #1 is We're able to do A, so we're going to do it).




It's an extremely fine point, but one could make the argument that using a modal in #1 (as opposed to "We will note that...", or just "We note that...") implies the authors could potentially run into difficulties with the proposition that "primary modals" are "truth-neutral", in which case one could say there's a hint of "tentativeness" in the advancing of a proposition there. A bit like this paragraph, really.


xna - Methods of Creating a "Lightning" effect in 2D


well i'm just wondering on the best way to go about create some form of "Lightning" effect to be used in a game, so for example:


-In my game, i would like to have this effect in the menus and in-game in some form of random weather system perhaps.



Just wondering on the methods available? I did read this blog post: http://drilian.com/2009/02/25/lightning-bolts/


And took a-look at the Lightning sample thats around. I like the method placed in the blog post, just really a bit unsure on how to create the vertices from the lightning segments. I would be great if someone could explain that seconded sub-heading (Adding glow) a bit more to me :).


But like i said, i'm really want to know if there's any other ways i could accomplish this?



Answer



Creating quads: http://msdn.microsoft.com/en-us/library/bb464051(v=xnagamestudio.10).aspx. You need only one quad per segment, as in image 9 "lightning vertices" of the linked article you mentioned.


Next, the glow is first created by having a bitmap, a simple circle will do nicely, which blends from hard bright center to soft darker outside, and alpha similarly solid in center and disappearing to edges. Black background works too, depending on shader. A shader with some blend effect smooths things out.


It really is the most impressive lightning effect, doing it with hand-drawn sprites only works if you have a scene for that specific situation.


Sunday, May 28, 2017

word usage - Is it 'thumb is up' in 'thumbs up'?



It was a thumbs up on the new filtration plant at Thursday's village board meeting



This is so common but then I never thought too deep unless I became a fan of English language after joining this site!





  • Is thumbs up actually (your) thumb is up? But then why thumbs? And not thumb's up - thumb is up (for this matter)?




  • Is thumbs up actually everybody's thumbs up? But then why not thumbs're up?



  • In above-mentioned case, it says a thumbs up. The article a?


Okay, while doing thumb(s)-up, you don't do it with both the thumbs but with one. So, it's actually thumb's up!




grammar - Two verbs in one sentence



I have just run into the sentence that has two verbs in my English textbook "


"Every morning, he left home dressed in a fine black suit."


Is that sentence correct ?


Thanks, I got the message.




assets - Cross-Platform Audio API Suggestions


I'm currently looking into adding sound to my game. I have seen OpenAL and SDL, but I would like to know what else is out there. Can you recommend any good cross-platform Audio APIs for game development?




unity - How can I create a radial animation that hollows out a shape from the inside?


I want to create the radial/circular animation seen in the explosions in this .gif of Flat Heroes.


I made an image using Illustrator of a radial ring (as below), but I'm not sure if this is the right approach. How can this be done?


Also, I would like to know how this could be extended to make similar animations for other shapes like squares and triangles.



Ring created in Illustrator



Answer



For a circular cutout we can do this with a little radius math and no textures at all. But since you mention wanting to extend to squares and triangles, I'll show a more general approach.


Animated particle system with star-shaped particles that wipe away from the inside.


First we create a texture in the shape we want, with a gradient falloff toward the interior. This gradient should follow the shape of the perimeter - we'll use it to control the shape of the inner cutout. For a circle, this can be a simple radial gradient.


Star-shaped gradient, white at the perimeter of the star and dark grey at the center.


Next we write a shader that reads this texture, as well as a threshold parameter, and displays only parts of the gradient that are brighter than the threshold as opaque, and everything darker as translucent, like so:


Shader "Unlit/RadialParticle"
{
Properties

{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
// Treat this material as transparent
Tags { "RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True" }
LOD 100

// Set up alpha blending

ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha

Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"


struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
// Vertex color field
// (used by the particle system to tint)
fixed4 color : COLOR0;
};


struct v2f
{
float2 uv : TEXCOORD0;
// Pass through color information to fragment
fixed4 color : COLOR0;
float4 vertex : SV_POSITION;
};

sampler2D _MainTex;
float4 _MainTex_ST;


v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
// Pass our color parameter through to the fragment
o.color = v.color;
return o;
}


fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);

// Hide any part of the image that's darker than
// the _Cutout parameter
col.a = saturate((col.r - i.color.a) * 10.0f);

// Replace the visible color of the image

// with the particle color
col.rgb = i.color.rgb;

return col;
}
ENDCG
}
}
}


Attach your shader to a material and configure it with your gradient texture and you're off to the races. :)


Here I've configured the shader to work in a particle system, reading the threshold from the vertex colour's alpha channel. That let me use the particle system's "Color Over Lifetime" curves to create the animation above quickly.


If you need to do this with just a single quad, you could instead expose _Cutout material parameter, and vary that material property via script.


Shader "Unlit/RadialSprite"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Color ("Color", Color) = 1, 1, 1, 1
_Cutout ("Cutout", Range(0, 1)) = 0.5

}
SubShader
{
// Treat this material as transparent
Tags { "RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True" }
LOD 100

// Set up alpha blending
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha


Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata

{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};

struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};


sampler2D _MainTex;
float4 _MainTex_ST;
// Add shader variables for our material properties.
fixed4 _Color;
float _Cutout;

v2f vert (appdata v)
{
v2f o;

o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}

fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);

// Hide any part of the image that's darker than

// the current alpha value of the particle color
col.a = saturate((col.r -_Cutout) * 10.0f);

// Replace the visible color of the image
// with the material color
col.rgb = _Color.rgb;

return col;
}
ENDCG

}
}
}

In my examples all the displayed colour is coming from the particle system / material parameters, but you could just as easily have colour detail in your texture, and store the cutout gradient in the alpha channel.


"Untangle"-Game AI


I am trying to program an AI for such untangle games like Untangle game.


I tried the following possibilities:


1) Just set one node after the other to a random place. If every node was moved once, start over with the first node in the list.


2) First move all nodes which have the most wrong connections. If all were moved once, move the nodes which have the fewest (but not 0) wrong connections. If all were moved but there are some left, move all which are left. If none are left start over.


3) Just 2) bust starting with the nodes with the fewest connections.


4)/5) As 2) and 3) but when I didn't move nodes which have only correct connections.


All of these approaches are too slow and inefficient.


Can anyone suggest a solution which does not depend so much on fortune?




Answer



I believe what you are looking for is a planar graph embedding algorithm.


If you want to solve the problem "properly" (in linear time), this thesis linked in this math.SE question seems to be what you are looking for.


Here is another paper on the subject A Linear Time Algorithm for Embedding Graphs in an Arbitrary Surface. Be aware that they are quite math heavy.


Edit: I found this implementation which should help: http://code.google.com/p/planarity/, particulary the planar graph drawing algorithm.


The pronunciation of tremendous


There are two different versions of British pronunciation for the word "tremendous" on Oxford and Cambridge dictionaries respectively, which one is correct?



Oxford: /trəˈmendəs/
Cambridge: /trɪˈmen.dəs/





Answer



What is involved here is less the pronunciation than the dictionaries' different standards for representing the pronunciation.


The vowel here is ‘reduced’: that is, it is not only unstressed but largely deprived of any character which distinguishes it from similar vowels. For a long time all such reduced vowels were regarded as allophones of a single phoneme, conventionally represented with the schwa, /É™/; and that is to this day a very common dictionary representation, as in your Oxford citation.


In the ‘40s and ‘50s, however, it was recognized that in one context there is a meaningful contrast between different realizations of this ‘phoneme’—in final syllables. The parade minimal pair (two words or phrases which differ in only one phonological element) is the contrast between Rosa’s and roses, which almost all native speakers of English pronounce differently. The reduced vowel in Rosa is the mid central vowel represented by /É™/; that in roses is a distinctly higher, a ‘near-close central unrounded vowel’. According to Wikipedia:



In the British phonetic tradition, the latter vowel is represented with the symbol /ɪ/, and in the American tradition /ɨ/.



Wikipedia says that the OED and The Oxford Dictionary of Pronunciation for Current English have recently introduced yet another symbolization:




A symbolization convention recently introduced by Oxford University Press for some of their English dictionaries uses the non-IPA "compound" symbol [áµ»] in words that may be pronounced with either [ɪ̈] or schwa. For example, the word noted may be represented [ˈnəʊtáµ»d].



So your two variant notations represent the same range of pronunciations in different ways. In your own speech it probably doesn’t matter at all which you use; nobody is likely to notice, unless you exaggerate. After all, even professional phoneticians didn’t care much about it for a hundred years.


word usage - What does "period" mean in this conversation?


What does the word period mean in the following context? It does not seem to be a part of the sentence.




— Could you please {do something}?
— I don't want to do that, period.




Answer



That is an intensifier:



Grammar. a word, especially an adverb, or other linguistic element that indicates, and usually increases, the degree of emphasis or force to be given to the element it modifies, as very or somewhat; intensive adverb.



In the example, it is equivalent to "at all".



I'd say that a more likely occurrence would be when some form of qualifier was originally specified:



"You don't want to go to football practice today?"


"I don't want to go to football practice, period."



unity - How to achieve 2D ski movements similar to Alto Adventure?


I'm trying to achieve 2d movement similar to Alto's Adventure with Unity 2D. When grounded I want the character to slide alone the terrain parallel to the slope, but I want to be able to freely rotate the character in mid air. In my current failed implementation I tried using a 2d collider attached to an gameobject with a movement custom script. I'm using vertical and horizotal raycast to detect the slopes, and the object rotates based on the angle of the slope. Long story short I've given up on this implementation for now.



Do you guys have any suggestions or pointers on achieving this type of movement?



Answer



In Alto's Adventure, the terrain is dynamically generated over time, by concatenating prefabricated patterns (for example the super steep slope where you can perform a triple backflip, or any other soft slopes) in a randomic way to keep the game various from play to play.


A possible implementation can be treating these "pieces" of terrain as vertices, from which it is possible to compute normal vectors and set the facing direction of your snowboarder accordingly.


About distinguishing between sliding and jumping, you can perform some checking during each game step:



  • If the user pressed/tapped for jump, perform the jump action. This applies if there's a collision underneath the player and only when key is pressed, not while it's being pressed;

  • If there's a collision under the player model:

    • Change speed and direction of the player according to the direction of normal vector of the terrain - to draw the player standing upright;




  • Else, if the player is mid-air:

    • If input key is being pressed, increase the drawing angle; if not, do nothing or change it to reach the right value to draw the player upstanding.




While the terrain is generated dynamically by jointing pre-made pieces of terraing, interacting objects - such as rocks, fireplaces, roofs, coins - are placed randomly so that they don't intersect each other (exception for coins, they can be both below or above a grind wire, for example).


objects - Make it happen?


We use the phrase make it happen.


But why don't we use happens since it has the third-person pronoun it?


Why not



Make it happens





Answer



This is tough!


I think it goes same with let. The only thing I can make out is make or let does not directly involve the third person. Said that, the third person is not doing things but they are indirectly involved, without their consciousness. I'm not sure how to put it correctly in words!



Make him study -he does or does not study, yet
Let her go -she is not directly involved in 'going'
and so on...



All above mentioned examples don't involve the third person doing things directly. The rule is when they do it directly, we apply 's. And thus, when we say "make/let it happen, the it does not perform action directly as the subject.



Say--



It goes - a subject doing things directly, by itself
Let it go - Here, the subject does not do things directly



[This is the best thing I could come up with! Native's inputs will be very useful and I'm so curious for their comments!]


infinitives - I hope you are right/you to be right



Why is



I hope you are right



written in that way and not



I hope you to be right





Saturday, May 27, 2017

c++ - SAT, How Do I Find The Penetration Vector?


I've just successfully implemented Separating Axis Theorem (SAT) in my game but I was wondering how do I find the penetration vector? I heard it can be useful for collision response. e.g. The harder they collide the harder the response.


I want the penetration vector so I apply it to the position of an object when it is current penetrating an other so I can move it back outside of the other object's bounds.


Here is my code so far.


Any help would be much appreciated,



Thanks in advance.



Answer



The classic way to do this is the GJK algorithm. It's a fairly complicated algorithm with a lot of moving parts, so might be tricky to implement. However, there are many implementations out there on the Web that you might be able to adapt.


A simpler way to get an approximate penetration vector might be to leverage the SAT itself; when you iterate over all the possible separating axes and check for overlap on each, keep track of which axis has the shortest overlap and use that as the penetration vector.


prepositions - Difference between being at/of/in someone's service


What's the difference between being at someone's service, of someone's service, and in someone's service?



Answer



This sentence should help clarify the differences between these:



The butler Mr. Dawkins, previously in the service of Lord Halsey as his valet, and having been of service to Lady Bucket by helping her find her lost Persian cat, said to Lord Bennett, "I am at your service, sir."




To be in (someone's) service means that you are employed by that person in some kind of service role.


To be of service (to someone) means that you have assisted or will assist them in some way. It is not necessary for you to work in service to do this. Anyone can be of service to anyone else.


To be at (someone's) service means that you are offering (or someone else has offered) your (usually temporary) help to someone, in a formal and deferential manner. Again, anyone can be at anyone else's service.


The use of the word "service" in all three relates to an older meaning of the noun, related to servant, a collective term for the various professions employed by a wealthy (or at least nominally upper middle class) family to do domestic tasks. These included such jobs as butler, valet, housekeeper, maid, chauffeur, groundskeeper, footman, cook, etc.


This was much more common a hundred years ago than it is today. Still, there are still many people who work "in service" -- but who are not called "servants", which nowadays is considered demeaning. Instead they may be collectively referred to as "the help".


If you are "of service" you have helped someone in the way a servant would have done. To be "at someone's service" is to offer your help as if you were their servant. Neither is particularly negative, however, since the acts are presumably voluntary.


Note this does not include "customer service" or "food service" or any of the many jobs that interact with the public, nor does it (usually) include people who work in hotels, spas, cruise ships, and other temporary lodgings, which are considered part of the "hospitality industry". While any of these may be "of service" or "at someone's service", I think they would not describe themselves as "in service".


At least not in the US. It might be different in other countries.


2d - Obstacle Avoidance steering behavior: how can an entity avoid an obstacle while other forces are acting on the entity?


I'm trying to implement the Obstacle Avoidance steering behavior in my 2D game.


Currently my approach is to apply a force on the entity, in the direction of the normal of the heading, scaled by a number that gets bigger the closer we are to the obstacle. This is supposed to push the entity to the side and avoid the obstacle that blocks it's way.


However, in the same time that my entity tries to avoid an obstacle, it Seeks to a point more or less behind the obstacle (which is the reason it needs to avoid the obstacle in the first place).


enter image description here


The Seek algorithm constantly applies a force on the entity that pushes it (more or less) in the direction of the obstacle, while the Obstacle Avoidance algorithm constantly applies a force that pushes the entity away (more accurately, to the side) of the obstacle.


The result is that sometimes the entity succesfully avoids the obstacle, and sometimes it collides with it, depending on the strength of the avoidance force I'm applying.



How can I make sure that a force will succeed in steering the entity in some direction, while other forces are currently acting on the entity? (And while still looking natural).


I can't allow entities to collide with obstacles when realistically they should be able to easily avoid them, doesn't matter what they're currently doing.


Also, the Obstacle Avoidance algorithm is made exactly for the case where another force is acting on the entity. Otherwise it wouldn't be moving and there would be no need to avoid anything. So maybe I'm missing something. Thanks




meaning in context - Usage of 'should' versus 'would'


I was wondering if someone could explain the subtle difference between these sentences:


1) Monday should be fine.


2) Monday would be fine.


This is in the context of someone asking if they could help me out on Monday instead of on Sunday. I am a little confused about the difference between the usage of 'should' and 'would' here. Both seem to fit. I personally seem to prefer 'should' but I can't explain why. Any help would be appreciated.



Thanks.



Answer




1) Monday should be fine.


2) Monday would be fine.



Should in sentence 1 is not the same use of should that we find in examples such as:



  • What should I do?

  • You should apologise.


  • You should eat five portions of fruit and vegetables every day.


The sentences above are asking for advice or giving advice. We can think of advice here like a form of weak obligation. If someone gives us advice, there is some pressure on us to do that thing - but we don't have to do it - it is our decision. This kind of meaning, when we talk about obligation and permission, is called DEONTIC modality.


Sentence 1 is NOT about deontic modality. This type of should is about EPISTEMIC modality. Epistemic modality is about knowledge and belief. Think about the following sentences:



  • It might be in box 3.

  • It should be in box 3.

  • It must be in box 3.


The first example above shows that the speaker has a weak belief that it is in box 3. The second sentence shows that the speaker has a fairly strong belief that it is box 3, but she's not certain. The last example shows that the speaker is certain that it is in box 3.



In the Original Poster's example, (1) indicates that the speaker has a strong conviction, a strong belief, that Monday will be fine. Of course this is the technical meaning of what they are saying. The effect of saying this sentence is probably "Yes, choose Monday".


Would in sentence (2) indicates a logical result of choosing Monday. The sentence is like the last part of a conditional:



  • If you chose Monday, Monday would be fine.


Here the speaker is definite about the fact that the result of choosing Monday is it's being fine. They aren't indicating any doubt about it. Again the effect in the conversation is probably "Yes, choose Monday".


Hope this is helpful!


Friday, May 26, 2017

algorithm - Implementation of finding an index in a 1D array for a triangular grid


Am using a while loop to find an index within a 1D array, is there an easier, less-time-consuming and/or mathmatical way to find the index?


Consider the next grid:


 4   o
|\
| \
| \
3 o---o
|\ |\

| \ | \
| \| \
2 o---o---o
|\ |\ |\
| \ | \ | \
| \| \| \
1 o---o---o---o
|\ |\ |\ |\
| \ | \ | \ | \
| \| \| \| \

0 o---o---o---o---o

0 1 2 3 4

To find an index in the triangular grid within a 1D array I have the next function:


//int size = 5;
int getindex( int x, int y )
{

int columnCount = size;

while( y-- > 0 ) x += columnCount--;

return x;

}

The array (The numbers within the parenthesis are the coordinates and to simplify your view, in reality the (x,y) is in its whole the data):


pointdata data[ 15 ] = {
(0,0), (1,0), (2,0), (3,0), (4,0),
(0,1), (1,1), (2,1), (3,1),

(0,2), (1,2), (2,2),
(0,3), (1,3),
(0,4),
};

Answer



This is rather problem to sum numbers between n and m, which is pretty widely known: it is sum of numbers 1 to m minus sum of numbers 1 to n(n-1 infact, but it gets eliminated in the code) plus x, ofcourse. In your example, it is:


index = columnCount * ( columnCount + 1 ) / 2 - ( columnCount - y ) * ( columnCount - y + 1 ) / 2 ) + x;
plus, since column count is static (presumably), you can pre-cumpute the first part or even better just use total length of your array.


multiplayer - how should a server handle client actions?


So I've just started trying to make a multiplayer pong game and I have read a lot of different ways to code the connections. However, I read somewhere that you should have the inputs sent to the server queue up and then the server just processes it at fixed intervals. However, if this is done, how does the server know, process, and send accurate data based on the time the action was sent? Because if the data is just queued up, if something happens like 100 ms after another but the server processes them at the same time, wouldn't that mess up the synchronization of the game? Should the server instead be coded to handle the client actions immediately even if it costs a lot of cpu etc in larger games?




prepositions - Is "He is on the swim team" correct?


I have read the sentence below:




He is on the swim team.



My questions are:




  1. Why use the preposition "on" ? Can I use "in"?




  2. What's the difference between "on" and "in "?





  3. Can "the swim team" be replaced with "the swimming team"?






sentence meaning - What does "I am off to the doctor" mean?


In this video a well-known man says



I am off to the doctor.




I think it means I am going to visit my doctor. However another rendering occurred to me; can it mean I am not at work due to the order of my doctor?



Answer



Using the first definition here:



Away from the place in question


the man ran off


she dashed off to her room


we must be off now



So you could say:




I am leaving [here] for the doctor['s office].



I'm off emphasizes a bit more that the speaker is leaving wherever they currently are while going is more generally stating that you're heading in that direction.





can it mean I am not at work due to the order of my doctor?



No. It would never mean this.


relative clauses - Omitting "who is" in "I would like to date a girl [who is] at least of my intellect"


Instead of



I would like to date a girl who is at least of my intellect.



can I say



I would like to date a girl at least of my intellect.




by dropping the phrase "who is"? What I try to mean is:



I would like to date a girl whose intellect level is at least the same as mine.





Thursday, May 25, 2017

meaning in context - "My older brother, Ted, is a good ten years older than me". Does 'good' mean 'at least or more' in this case?



Below is a paragraph in my English textbook:



Andrea - There are six of us in our family, my parents, me, the twins and my older brother, Ted. Ted is a good ten years older than me and the twins – they are girls – are two years younger than me. We had a good childhood out in the countryside. My parents were always busy with the farm and so we didn't get the help with school work and things like that that children get today. But my parents were very loving, especially my father. I regret not helping more around the farm because now I realise that it must have been very hard for my parents, especially as my grandparents lived so far away.


Source: http://sinhngu.com/f_view.asp?CID=1908&QID=17677



The Oxford Dictionary says the word 'good' in this case means



5.1 Used to emphasize that a number is at least as great as one claims.
‘they're a good twenty years younger’




The Longman Dictionary also gives the similar meaning:



a good three miles/ten years etc
at least three miles, ten years etc, and probably more
He’s a good ten years younger than her.



However, I feel it quite strange. Because if Ted is a person who Andrea hasn't known yet, then she can guess he is at least ten years older than her (by looking at his appearance or his photograph). In the passage above, Ted is her older brother, then Andrea must know exactly how old Ted is. He must be ten years older than her. It cannot be less than or more than 10 years (8, 9, 11 or 12 years). That's why I feel it quite strange when I understand the meaning of that sentence: '...Ted is at least and probably more ten years older than me...'


Could you kindly tell me whether I have understood that sentence correctly?




Meaning of "it is" at the end of sentence


I was googling but I couldn't find any answers:


What is the precise meaning of the words 'it is', when they are used in a way




  • Are we going to the cinema on Friday or Saturday?

  • I don't have any time on Friday.

  • OK, then Saturday it is.






xna - How can I improve my isometric tile-picking algorithm?


I've spent the last few days researching isometric tile-picking algorithms (converting screen-coordinates to tile-coordinates), and have obviously found a lot of the math beyond my grasp.


I have come fairly close and what I have is workable, but I would like to improve on this algorithm as it's a little off and seems to pick down and to the right of the mouse pointer.


I've uploaded a video to help visualize the current implementation: http://youtu.be/EqwWcq1zuaM


My isometric rendering algorithm is based on what is found at this stackoverflow question's answer, with the exception that my x and y axis' are inverted (x increased down-right, while y increased up-right).


Here is where I am converting from screen to tiles:


// these next few lines convert the mouse pointer position from screen 
// coordinates to tile-grid coordinates. cameraOffset captures the current
// mouse location and takes into consideration the camera's position on screen.

System.Drawing.Point cameraOffset = new System.Drawing.Point( 0, 0 );
cameraOffset.X = mouseLocation.X + (int)camera.Left;
cameraOffset.Y = ( mouseLocation.Y + (int)camera.Top );

// the camera-aware mouse coordinates are then further converted in an attempt
// to select only the "tile" portion of the grid tiles, instead of the entire
// rectangle. this algorithm gets close, but could use improvement.
mouseTileLocation.X = ( cameraOffset.X + 2 * cameraOffset.Y ) / Global.TileWidth;
mouseTileLocation.Y = -( ( 2 * cameraOffset.Y - cameraOffset.X ) / Global.TileWidth );


Things to make note of:




  • mouseLocation is a System.Drawing.Point that represents the screen coordinates of the mouse pointer.




  • cameraOffset is the screen position of the mouse pointer that includes the position of the game camera.




  • mouseTileLocation is a System.Drawing.Point that is supposed to represent the tile coordinates of the mouse pointer.





If you check out the above link to youtube, you'll notice that the picking algorithm is off a bit. How can I improve on this?



Answer



What you need is some good old fashioned matrix math.


Let's say you have two spaces:



  • World space - where the tiles reside

  • Screen space - where the mouse pointer is



You want to check the mouse coordinates against the tiles. But first, you will have to convert your mouse coordinates from screen coordinates to world coordinates.


That sounds harder than it is. Let's pretend the tiles are not laid out isometrically, but in a grid. Like this:


Original


I've added numbers that represent the tiles in memory. For example, 0 would be m_Tiles[0].


Here, it's easy to see which tile is selected. In pseudocode:


vec2 pos = mouse.pos - tileset.pos_upperleft;
int index = ((pos.y / tileset.tile_height) * 2) + (pos.x / tileset.tile_width);

In this case, that gives us an index of 2, which is correct.


But watch what happens when we rotate the tileset 45 degrees:



Image2


Now we're selecting a different tile altogether! How can we fix this? Well, in two ways:



  • Rotate the tileset to fit the screen coordinates (world space to screen space)

  • Rotate the mouse coordinates to fit the world coordinates (screen space to world space)


We're going for the first method here. It's great for 2D selection because it allows us to keep the rest of the math the same.


First, let's build a matrix that defines the transformation of our tileset. We want to rotate the tileset by 45 degrees, so we'll take a 3x3 matrix (2D matrix) and add a rotation. Then we inverse the result. Think of it this way: to go from world space to screen space, we must rotate by 45 degrees. So to go the other way around, we must rotate by -45 degrees.


Now the code becomes:


mat3x3 transform = mat3x3.identity();

transform.rotate(45.0);
transform.inverse();

vec2 tileset_transformed_pos = transform * vec3(tileset.pos_upperleft.x, tileset.pos_upperleft.y, 1.0);

vec2 pos = mouse.pos - tileset_transformed_pos;
int index = ((pos.y / tileset.tile_height) * 2) + (pos.x / tileset.tile_width);

As you can see, we use the transform matrix to transform the upperleft corner of the tileset. Now the tileset coordinates are in the same space as the mouse coordinates.


But we're not there yet. The tiles are also squashed a bit. The same effect can be achieved by scaling the matrix by a certain amount:



Squashed


Here I've scaled the whole tileset on the y-axis to 63%, which looks remarkably like an isometric projection. The full pseudo-code:


mat3x3 transform = mat3x3.identity();
transform.rotate(45.0);
transform.scale(1.0, 0.63);
transform.inverse();

vec2 tileset_transformed_pos = transform * vec3(tileset.pos_upperleft.x, tileset.pos_upperleft.y, 1.0);

vec2 pos = mouse.pos - tileset_transformed_pos;

int index = ((pos.y / tileset.tile_height) * 2) + (pos.x / tileset.tile_width);

Obviously you will have to tweak this a bit, but it should give you a sense of where to begin.


rigid body dynamics - How can I implement revolute (hinge) joints in a 2d physics system?



Further to my previous question on fixed joints, I am now going toe-to-toe with hinge joints in 2D physics. Though the answer to the previous question was excellent, I have come across a few problems in extending it to hinge joints.


My approach was to extend that given here by implementing the following algorithm:



  1. Find the 'target' point for both hinge points by taking the midpoint between them (I actually use mass to give a ratio here but assume the bodies are of equal mass -- in my simulation they all are). The target point is labelled T in the diagram below.

  2. For body a, find the angle between the hinge point A and the target point T. This is done by transforming T from global space to local space, then taking the difference of Atan2(y, x) for each point - this should return the angle between them.

  3. The body a is then rotated by a matrix created from this angle, so that A and T now lie along the same vector. a is then translated by T-A; now A should be at T.

  4. Repeat steps 2 and 3 for body b.


The algorithm seems logical to me, but I have found that there is some kind of stability issue whereby the bodies will stay constrained for a short time, then as the angle between the two bodies becomes slightly more acute (in either direction), they will both shoot off at high velocity. The number of constraint iterations is not the issue as far as I can tell - the same problems occur at 1 iteration as at 10.


Diagram depicting two bodies with one hinge joint



Pseudocode to my algorithm given below:


// EntityA and EntityB are the two objects
// HingeA and HingeB are represented as vectors relative to their local transforms
Transform tA = EntityA.Transform;
Transform tB = EntityB.Transform;

Vector2 delta = tA.LocalToGlobal(HingeA) - tB.LocalToGlobal(HingeB);

// Locate the target in global space by finding the midpoint of the delta vector A-B
// then translating it by B

Vector2 Target = (delta * 0.5) + tB.LocalToGlobal(HingeB);

// Locate target in Entity A's local space
Vector2 TargetA = tA.GlobalToLocal(Target);

// Avoid undefined behaviour for Atan2
if (TargetA != Vector2.Zero && HingeA != Vector2.Zero)
{
// Get the angular difference between A and T
float angleA = Math.Atan2(TargetA.Y, TargetA.X) - Math.Atan2(HingeA.Y, HingeA.X);

tA.Angle += angleA;
}

// Re-convert the target to local co-ordinates and translate EntityA towards it
tA.Pos += tA.GlobalToLocal(Target) - HingeA;

// Repeat for entity B...

Am I on the right track with this algorithm? Is there some minor detail I have missed that is aggravating the simulation?




procedural generation - How can I optimise a Minecraft-esque voxel world?


I found Minecraft's marvelous large worlds extremely slow to navigate, even with a quad core and meaty graphics card.


I assume Minecraft's slowness comes from:



  • Java, as spatial partitioning and memory management are faster in native C++.

  • Weak world partitioning.



I could be wrong on both assumptions. However, this got me thinking about the best way to manage large voxel worlds. As it is a true 3D world, where a block can exist in any part of the world, it is basically a big 3D array [x][y][z], where each block in the world has a type (i.e BlockType.Empty = 0, BlockType.Dirt = 1, etc.)


I assume that to make this sort of world perform well, you would need to:



  • Use a tree of some variety (oct/kd/bsp) to split all the cubes out; it seems like an oct/kd would be the better option, as you can just partition on a per cube level not a per triangle level.

  • Use some algorithm to work out which blocks can currently be seen, as blocks closer to the user could obfuscate the blocks behind, making it pointless to render them.

  • Keep the block object themselves lightweight, so it is quick to add and remove them from the trees.


I guess there is no right answer to this, but I would be interested to see peoples' opinions on the subject. How would you improve performance in a large voxel-based world?




Wednesday, May 24, 2017

unity - How do I wait to execute code?


I'm trying to make a relatively simple elevator (which essentially teleports the player), but I don't want it to instantly teleport them. I want the player to enter the collider, wait 2-3 seconds, and then do it to take make it seem somewhat more natural.


My code thus far:


using UnityEngine;
using System.Collections;


public class Teleporter : MonoBehaviour
{
public GameObject TeleportTo;
//public Material NewSkybox;

void TimerInvoke()
{

}


void OnTriggerEnter(Collider other)
{

Vector3 displacement = other.transform.position - this.transform.position;

other.transform.position = TeleportTo.transform.position;
other.transform.position += displacement;

//RenderSettings.skybox = NewSkybox;
}

}

Also if possible I'd like to stray away from coroutines. How should I do this?




android - Road parallax background



I am a beginner in game development. I want to create a parallax background that merges at the front and expands at the bottom. I'm sure there is a way to do this, but I'm missing something. My parallax background is working fine but didn't merge from start to bottom.


Any guidance? Thanks!


Code for my parallax:


private BitmapTextureAtlas mAutoParallaxBackgroundTexture;
private TextureRegion mParallaxLayerMid;

this.mParallaxLayerMid=BitmapTextureAtlasTextureRegionFactory.
createFromAsset(this.mAutoParallaxBackgroundTexture, this,"road.png", 0, 0);

back_ground = new Sprite(0,0,CAMERA_WIDTH,CAMERA_HEIGHT,this.mParallaxLayerMid);


autoParallaxBackground = new AutoParallaxBackground(20, 30, 40, 50);
autoParallaxBackground.attachParallaxEntity(newParallaxEntity(15.0f,back_ground));
scene.setBackground(autoParallaxBackground);

I'm trying to make parallax background like in these screen shots.



Answer



Your question is a bit rough but if I'm following correctly, you want to make it so the background is stretched horizontally as it moves towards the bottom of the screen, giving it a somewhat isometric view and a more angled perspective.


Just as a warning, I've no direct android development experience myself so this is going to be largely theoretical. Others may be able to tell you what parts of this are feasible or better methods to do so.


Camera Method



Easy way to do this off the top of my head is to tilt an overhead camera pointed at a top down surface.


                           Rough Camera Example


That would allow you to do all your game logic without regards to the perspective drift (something moving forward along the road would naturally shrink as it moved away). Of course this means that there will be parts of your surface that are clipped by the bounds of the screen, but depending on how you handle your gameplay this may or may not be an issue.


Shader Method


Another way to handle it would be to implement some form of shader that sampled the surface differently based on Y position on screen. Again, I'd likely render my scene as a rectangle (straight top-down, no perspective) and use that as what gets sampled so all the assets get the effect and not just the background. Using a system like that you could specify a percent amount to sample from at the bottom of the screen and the top and adjust them to taste.


An example of using that method. Say you had a surface and you wanted 50% at the bottom and 100% at the top:


                         Rough Shader Example


When you go to draw to your screen, what is actually displayed is entirely within the red. At the bottom of the screen, the left most pixel samples from the 25% mark and the right most pixel samples from the 75%. This does mean you'll have to deal with stretching up close/loss of detail at distance, but things like image resolution and how dramatic you make the difference between "near" and "far" will allow you to adjust it until it feels right.


Cheating!


If both of those have issue, or if it just sounds like too much of a pain, then I'd recommend cheating. Make your background relatively static with the proper tilt to it and only move non-static elements along it.



Using the road example, the lines down the middle and the things along the sides of the road. You'll have to scale them up slightly as you move them down the screen, but you can get a fairly decent illusion of perspective/depth with very little cost this way provided you either don't turn or come up with a decent way of handling them. This is something very similar to what a number of old resource limited games would do in this situation.


Hope one of these is something close to what you were looking for.


grammar - “While she is sleeping, we...” – what verb tense comes next?



While she is sleeping, we decided to wake her up.




Trying to understand this grammar. Should we use decide or decided to?


Edit:


Okay, the reason I'm asking is because I'm trying to make some captions for a video. So the video will be



"While she was sleeping, we decided to...."



and afterwards we have another caption follows..



"Now she is awake..."




Using 'Now' usually uses present tense afterwards. If we use past tense earlier, it does not logically flows well with present tense later. So I don't know if I should use present or past tense.



Answer




While she is sleeping, we decided to wake her up.



That's simply wrong. You are mixing a present tense with a past tense. You could say:



While she is sleeping, we decide to wake her up.




This is pretty rare usage, though. In English we almost never give a narrative in the present tense. Present tense is primarily used to, (a) describe something literally happening right now. "Where is Bob?" "He is out to lunch." Or (b) to describe a continuous state. Like "Paris is the capital of France." It has been for a while and it is now and it probably will be for some time in the future.


More likely would be:



While she was sleeping, we decided to wake her up.



Also, when you have a conditional expression referring to a future event, you use the present tense, though logically you might think you should use the future tense.



WRONG: While she will be sleeping, we will decide whether to wake her up.


RIGHT: While she is sleeping, we will decide whether to wake her up.




(There's probably a name for this, it's not really the present tense, it's some kind of future conditional tense. But I don't know the name.)


Similarly:



If the stock market goes up, I can retire early.


Unless you stop acting irresponsibly, you will never get a good job.



Etc.


word usage - How to refer to the different types of first names of a person?


In Dutch (and other languages) people have have different types of first names. First, there is the Christian name or given name, which is the official name of a person and is used for official documents etc. Then there is the first name that is used on a regular basis. The literal translation of the Dutch word for that is 'calling name' (roepnaam). Finally there is the nickname that close friends and family use.


My sister's name is a typical example. Her given name ('birth name' in Dutch) is 'Elisa Hermina', the name used by everybody, however, is 'Lisette' and the name used by family and close friends is 'Jet'. They could of course also be the same.


For an English paper I am writing, I need to distingish between the names. Which words could I best use for each of the names?


I know 'calling name' is also used in english and also seems to have a similar meaning. Does it indeed have exactly the same meaning a the dutch roepnaam?




java - Using seeds for rng. A reliable way of saving bandwidth?



Imagine a server-client game application.


While running, the server is constantly generating numbers for various random events and sending them over the network to inform the clients of the result.


I realized it would save alot of bandwidth if I made my rng deterministic and would only transmit a seed value at the start of the game and the number of random calls that have been made on that random instance in the past so that my clients can reproduce a similar random instance and the next generated value will be the same for all clients. Is that a reliable option in terms of security and synchronization and apart from predictability?



Answer



Entropy


Sending random numbers and sending seeds is the same thing: sending entropy.


Consider that in the case of sending random numbers, you can interpret that each random number sent is a seed for a random number generator used by the client, and this random number generator has a cycle of only one number.


Consider also that if you use a random number generator that generates 2^63-1 values with a seed of 32 bits of entropy, then the sequence has very little entropy... which means they are easy to crack.


Have a look at "Cracking Random Number Generators" from all that jazz.






My question refers to an imaginary server-client application and was meant in general. So you can assume a worst case scenario



I do not know about worst case scenario. Yet, I will take a case that I think is fairly high: 2 bit per millisecond.


So, that is 2000 bits per second, or if you prefer it is about 33 bits (roughly an int32) per frame in a 60 fps game.


That mounts to slightly below 7MB per hour. It does not sound that crazy at this scale, does it?



Numbers are the same for all clients.



Generate a random file, and allow clients to download it. Use something based on TCP so that they all get the same bits. You server would have to generate one file per hour, and there should be some metadata so the clients can synchronize.



Yes, HTTP would work. Note: We are not talking bandwidth yet.


However, when it comes to generate the random numbers, the standard random number generators will start to show patterns.


See Random.org article on statistical analysis.


The following is from "Cracking Random Number Generatos" (part 3):



A much more popular PRNG algorithm is the Mersenne Twister. This is used by Ruby's rand() function, Pythons random module, and PHP's mt_rand() function.


The Mersenne Twister was invented in 1997. The most common implementation of it uses an internal state of 624 32 bit words (integers).



So, with only 624 * 32 bits = 19968 bits (a little less than 20 KB) you can work out the sequence, if you are generating numbers this way, sending more numbers gives no more entropy to the client.


In fact, if you need strong guarantees on the random numbers (for example, if you are running an online casino), consider random.org services. They can generate over 2000 bits per second, so I would recommend their service if you need this many random numbers.



Note: For this rate of output, something like Microsoft Crypto API will work ok.




Security



you can assume a worst case scenario



You want an algorithm that generates random numbers that has the property that an attacker won't be able to predict the next numbers. That is, you want a Cryptographically secure pseudorandom number generator. If we are talking about Java, our first stop is SecureRandom. With SecureRandom you do not have control over the input entropy, the system will gather entropy from whatever source the underlying operating system provides.


From SecureRandom (Java Platform SE 8 ) - Oracle:



Note: Depending on the implementation, the generateSeed and nextBytes methods may block as entropy is being gathered, for example, if they need to read from /dev/random on various Unix-like operating systems.




Otherwise, you will need a third party solution (or cook one yourself). I suggest looking for an implementation of Fortuna which will give you more control on how you provide entropy.





What do you mean by "stepping between sender and receiver"?



I think Bálint was talking about Man in the Middle attacks.


The bad news is that a third party could try to pretend to be server and give you false numbers. Use a secure channel (SSL, HTTPS, etc...).


The good news is that everybody gets the same numbers. So there is no need for session or tokens, as the client does not need to identify itself. Which also means that session hijacking or impersonation are non issues when it comes to this random number generator.


However, a side effect is that it could be possible (with a bit of reverse engineering) to figure out how to create a tool that can download the data files and run the random number generator ahead of time, and perhaps do predictions of what will happen in the game. Which is another reason to generate small files often (multiple in a day) instead of generating a large file for the day or the week.



Edit: I guess you could use authentication to protect the data files. However that just means that the guys doing the tool need a valid account. I suggest to not bother. Assume they will make the tool.




Synchronization


Every client must do the same rolls. That means that you need to design the game in such way that rolls are not conditional.


The reason is that if a client does a roll but another client does not, they are now out of sync.


This also means that you should have a plan for exactly how the random number generator will be used.


Consider using two random number generators. One for the big stuff that needs to stay in sync, and one for any other stuff that does not have to be as strong as the first one.


Then, there is timing. You wan two things to make this work:



  • Publish the data files and the time at which they should start using it.


  • Have a side channel to synchronize clocks.


Note: Another thing you can do, is limit the number of times a generator is used. If you game knows how many numbers it has to generate, that is. Which I recommend you to know.


The server should have available the next data file and at what time the clients should use it. Then the clients will download it and prepare a random number generator ahead of time and when the time comes they switch to the new one... and start downloading the next.


However, we need them to switch to the new one at the same time. Which is why we need to synchronize clocks. And synchronize often. A query to an ntp often.


What if you used a generator a few extra times? Go back and redo them with the new one. I would suggest to introduce a natural exit point when the change is happening (having natural exit points is good anyway).




Bandwidth


If you want to run SecureRandom, it must be in the server because you cannot seed it. In this case, you will be serving those 7MB files.




you can assume a worst case scenario



21 million users?


20 million * 7 MB / hour = 311.1 GB/s.


About 102 PB per month. Note: Those are PetaBytes - TeraBytes are suddently small.


I woudl have said Get a global CDN solution and let them handle the traffic. But this crazy.


Let us put some of the work on the client. If we use Fortuna random number generators, we can provide about 12KB of useful entropy and have it virtually never run out (Fortuna reseeds itself).


If we stay with the idea of providing entropy once per hour,


20 million * 12 KB / hour = 533.3 MB/s.


About 176 TB per month.



It could work with only 2KB of entropy (I was compensating for the entropy input being infrequent). In that case we would be talking of only about 30 TB per month.


Get Amazon CloudFront.


Tuesday, May 23, 2017

conjunctions - Can I omit "that" in the following case?



She had eyes so far apart from each other that looking at them made me feel dizzy.



Can I omit the that in this case? Why and why not?



Answer




She had eyes so far apart from each other that looking at them made me feel dizzy.




No, you cannot drop the subordinating conjunction that here. A subordinating conjunction is necessary to connect the two parts of the sentence.


Sometimes a subordinating conjunction can be dropped, but not in this case. Usually we omit a subordiating conjunction after a "reporting verb" like to tell, learn, discover, feel etc.:



She had eyes so far apart from each other! I told her (that) they made me feel dizzy. I really felt (that) they made me dizzy.



Had it been a relative pronoun, you also could've dropped it:



I felt dizzy looking into those beautiful eyes (that) she had.



Here, we can omit the relative pronoun that because it serves as the object of the relative clause "that she had".




She had what? She had [that]. (She is the subject, that is the object)



past tense - What is the difference beetween "You decided" and "You did decide"


I know that "You decided" is simple past, but I've never ever seen this kind of construction until I listened it in a song (You did decide):



Pronoun + Simple Past(Past assistant did) + simple present




Then, what is the difference? Does this construction really exit?



Answer



In simple sentences, we don't usually use the verb to do to indicate the tense(past/present). It only occurs in a question(interrogative)



did you decide it? -past


do you decide it? -present



However, you can use it in simple sentence for emphasis




You decided it. - simple past tense


You did decide it. -simple past tense but more emphatic.



EDIT: It also occurs in negative sentences



I don't decide it


I didn't decide it



legal - Can I use Playstation controller button icons in my game?



I'm currently working on a game that will be released on PC with controller support, and I'm trying to find a way on how to best represent controller icons within the game.


enter image description here


I'm assuming I can't simply use Playstation or Xbox controller icons in my game without having some form of license first (right?).


So how would it be best to convey something like 'Press X to interact' in a PC game for controllers?



Answer



While the letter X is not copy protected, the specific cross used on the controller, along with the other shapes: enter image description here, are trademarked. Using your own art to represent the buttons (as in your example image), should be OK under fair use, specifically nominative fair use. Where the qualifications for nominative fair use are one of the following situations:




  • The product or service cannot be readily identified without using the trademark (e.g. trademark is descriptive of a person, place, or product attribute).

  • The user only uses as much of the mark as is necessary for the identification (e.g. the words but not the font or symbol).


  • The user does nothing to suggest sponsorship or endorsement by the trademark holder. This applies even if the nominative use is commercial, and the same test applies for metatags.



In this case, you're not trying to use the symbols as your own, but instead are directly referring to Sony's trademarked buttons, which likely falls under the first category.


If you're unsure, talk to a lawyer. If you're taking advice from someone on the internet, talk to a lawyer.


word usage - "It is the category where most of the processed data falls into" - is it correct?


Is the following sentence correct? I have some doubts about "category where ... fall into" phrase.



It is the category where most of the processed data falls into




Answer




Use of a preposition with where is non-Standard, because where itself stands for a preposition phrase. It's equivalent to in which or from which or at which or . . . which specific preposition is involved is inferred from the context. But the preposition is built in to the term where.


So if you're using your example in a context where Standard English is called for, you may say "the category where most of the processed data falls into" or "the category which most of the processed data falls into", but not "the category where most of the processed data falls into".


BUT: In some cases an extra preposition is necessary and acceptable. In particular, because where "defaults" to designating a location or a goal, adding from to designate an origin will often be necessary: "From where did you come?" (or "Where did you come from?"). Note, however, that this will not be necessary with a verb like get, which inherently implies an origin.


AND: It must also be acknowledged that in colloquial contexts it is not at all uncommon for a specific preposition to be added to make the specific meaning more explicit; and in these contexts it cannot be regarded as 'incorrect' or 'ungrammatical'.


Note, however, that such an 'extra' preposition is almost always stranded at the end of the clause; you will very rarely see it pied-piped to the position before where:



        always OK the category into which most of the processed data falls
        usually OK the category which most of the processed data falls into
colloquially OK the category where most of the processed data falls into
               not OK the category into where most of the processed data falls




present perfect - Why wasn't "When I was in Sharm El-Sheikh, I *have sunbathed* a lot" a good answer?



When I was in Sharm El-Sheikh, I .... a lot


A) Have sunbathed B) Was sunbathing C) Would sunbathe D) Sunbathed



why it can't be "have sunbathed" as verb sunbathe means to make the skin brown or darker and that has an affect and continue for a period of time so why it can't be A





punctuation - Capitalization of first letter after a dash



I'm in South Ossetia – yes, I managed to get a visa!



In this sentence, should "yes" be capitalised ("Yes") after the dash?




Monday, May 22, 2017

c# - How to share Unity High Scores on social media (Facebook , Google+ and Twitter)?


This may be a common question but as a n00b I have some confusion on achieving this .


I am on a small game project and I want the user to share his / her scores on social media after completing the game .


When they post , it should be something like "Hurrayyyy ! I Scored 12345 on -My Game App Name- , Can you beat my score ? Try it ." where '-My Game App Name-' and 'Try it' should be a link directing to Google Play / Windows Store etc .



My Idea is like this :-


Social Media


Here Share This on Facebook , Share This on Google+ and Share This on Twitter are 3 UI Images with Button component attached to them .


So when the player clicks on those buttons , they should post on social media .


So how to achieve this ? I got something here , but I don't know how to use that . I will prefer not to use Facebook Unity Plugin . So can I achieve this ? I need code in c# , not in JavaScript :)


I hope you will help me to figure this out .


Regards , NB :)




c++ - Efficient path-finding in free space



I've got a game situated in space, and I'd like to issue movement orders, which requires pathfinding. Now, it's my understanding that A* and such mostly apply to trees, and not empty space which does not have pathfinding nodes. I have some obstacles, which are currently expressed as fixed AABBs- that is, there is no unbounded "terrain" obstacle. In addition, I expect most obstacles to be reasonably approximable as cubes or spheres.


So I've been thinking of applying a much simpler pathfinding algorithm- that is, simply cast a ray from the current position to the target position, and then I can get a list of obstacles using spatial partitioning relatively quickly. What I'm not so sure about is how to determine the part where the ordered unit manoeuvres around the obstacles.


What I've been thinking so far is that I will simply use potential fields- that is, all units will feel a strong repulsive force away from each other and a moderate force towards the desired point. This also has the advantage that to issue group orders, I can simply order a mid-level force towards another entity. But this obviously won't achieve the optimal solution.


Will potential fields achieve a reasonable approximation given my parameters, or do I need another solution?



Answer



While potential fields may work, I imagine you'll have issues with sub-optimal paths and "local minimums" where your units will be trapped by surrounding obstructions. A* is suitable for 3D open space environments. It simply becomes an issue of generating a navigation mesh that fits your needs. You can even use structures like Octrees for navigational nodes. The smaller the maximum size of each octant, the smoother the path. Check out this article from Face to Face games (now defunct, added wayback link). A* combined with path optimization (like line of sight shortcuts) and steering behaviors and you'll be good to go! See the image below as an example of using an octree for path nodes:



word usage - Use of "yet", "however" and "but"


Here are some sentences with 'Yet', 'however' and 'and'





  1. She hasn't got many friends, yet everyone likes her.




  2. She hasn't got many friends, however, everyone likes her.





  3. She hasn't got many friends, but everyone likes her.





I'm actually confused with the use of ‘yet’ because it's quite similar to ‘but’ and ‘however’. So, how is ‘yet’ different from them? Could you please tell me how to distinguish the differences in the usage of them.




Sunday, May 21, 2017

tense - "Have had" versus "had"


How does the usage of "have had" and "had" differ?


Here is my example from my other question:



People who have had their belongings taken will turn into miserable people.



Here are the things I seem to have gotten from StoneyB's answers:




  • Have had is used for one-time occurrences, but had can be used for such occurrences as well

  • Have or simple present is used for something more habitual


So does that mean have had and had are interchangeable?



People who have had their belongings taken will turn into miserable people. [= "People who had their belongings taken will turn into miserable people."]



Is this assumption correct, or do they imply different meanings?


So a sentence like "people who smoke will get sick" means that a habitual smoker will get sick, but a sentence like "people who have smoked will get sick" means that if you have smoked even once in your life, you'll get sick. Is this exact?





british english - How to answer "Do you need a 5p bag"


I have troubles with this simple question: Cashiers do not understand my accent, so I want to find some answer that is easier to articulate.


When I answer " I already have one " - they never understand.



Is there any other option to say (apart of "No, thanks) that I have a bag (I brought it with me) that utilizes "better" vowels for non-native speaker?


British English UPD To those answering later: I want to improve my English pronunciation. The example in question is just one of the examples, not the whole issue, thus pantomimic clowneries could not be taken into account: NO, THANKS!



Answer



Cashiers want customers to get through the line quickly. They don't need justification. It is a simple YES/NO question. So "No" or "No thank you" to be more polite.




David Richerby made an excellent point in his answer below that you need to consider head nods too. In English speaking countries a head nod up and down means yes, while shaking side to side means no.


in a comment on David's answer nigel222 made another great point. It is "No, thanks" but "Yes please". That gives the person you're speaking to two chances to hear you: "something please" implies Yes, "Something thanks" implies No. Useful in a busy / noisy environment, as well as polite.


I guess the other point here is that you need to be sure that you're speaking loudly enough. Checkout lines are noisy.


So saying "No thanks" with a couple of side to side head shakes should get you through the line without a "Huh??" from the cashier.


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