Saturday, February 22, 2020

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 shape before



I assume that it's not correct because simple past is used for a finished action in the past, at a specific time. And being in a good shape it's not an action..




I have been in a good shape before



This sounds ok to me, because it's "change over time".



I had been in a good shape before (I broke my leg)



If it would have had a simple past at the end I believe this would have been the correct form.


I think this is what the theory says, but I've seen for many times people using past perfect without specifying a simple past and I don't understand whether it is correct or not.




word choice - I'm born or I was born, which one to use


Should I say I'm born in or I was born in?



Can I say I'm born in Paris in 1900, or should I say I was born in Paris in 1990?



Answer



"I was born in Paris in 1990" is the correct statement to use.


"I'm" is a condensed form of "I am" which is present tense, as you are talking about a past event "I was" is used.


xbox360 - XNA: How does threading work?



I would like to implement threading in my XNA game but I'm not sure how things work when compiling for the XBOX 360. Could someone elaborate on this?


For example, how many threads does XBOX support? I realize that XNA uses a special version of the Compact Framework. How does this affect the code during development? Do I implement things differently when developing for XBOX than Windows?


Thank you.




terminology - What is data-driven design?



I've been reading up on a lot of articles covering data driven design for games. It seems to come down to:




  • No hard coding

  • No game-specific code in the engine

  • Scripting for AI, cutscenes, et cetera.

  • Generalizing code for reusability

  • Component design

  • Modularity

  • Low coupling

  • Editors (for data, maps, scripts)

  • External data retrieval


  • Constants kept in text files (.ini or otherwise)

  • Expose data through editors for scripting and manipulation by designers


Now, my question is, is this understanding correct?



Answer



I'd say this is not correct. I believe the most important idea in data driven design is separating your data from what modifies (or updates) the data.


So going from a standard OO deep hierarchy like this:


class MyCreature{
vector position;
void update(){ position += 1; }

}

to a separate state and system


class CreatureState{
vector postion;
}

class MovementSystem{
list states;
void update() {

for each CreatureState state in states {
state.position += 1;
}
}

On of the most influential DDD paradigms at this moment are Entity Systems. Some nice resources to look up are:


http://gamedevrubberduck.wordpress.com/2012/12/26/a-hybrid-entity-system-component-architecture/


http://entity-systems.wikidot.com/


Of course as with all paradigms/ideas there isn't an exact definition and not everybody understands the same idea when talking DDD but this is what I believe the most important thing.


procedural generation - How to devise an algorithm for a person being on a walk?



The game is an isometric RPG. The map is tile based.


I'm creating a town for this game. And I want one of the characters to roam the town randomly, because she is on a walk with her children.


I tagged the tiles she can go on. And I created a simplistic algorithm that I, in my naiveness, thought would be enough. Here it is:


If the character is blocked out and can't move in any direction she waits 1s before checking this again. If she can move in only one of the 4 directions, she moves that direction. If there is more than one possibility: If she can go forward, she always has 50% chance of going forward; if she can go both to her left and to her right there is an equal chance she chooses either of those two directions; and finally, if she can turn back, that chance is 2x smaller than turning to her left and 2x smaller than turning to her right. So, if she can choose from all 4 directions, she will have 50% chance to go forward, 20% chance to go to her left, 20% chance to go to her right, and 10% chance to go back. Repeat the above every step.


This algorithm fails beautifully. The character mostly moves randomly in one place. If she gets on a square she almost can't leave it.


I thought the solution would be to increase the chance of her moving forward. So I made the chance to go forward 5 times bigger than doing anything else. But this proved to hardly improve things.


COuld you give me some hints, point me to the correct direction? Or at least tell me that this is not worth it and I should instead resort to giving her a predefined path? (Are there no algorithms to make a character roam a given set of walkable tiles?)




meaning - right hand to God - what does this mean?


From the science fiction movie Dreamcatcher (2003):



— Nine miles to Hole in the Wall.

— I think I can manage it.
— I'll bring the snowmobile back and get you both. Now, Pete, you listen to me. Don't go back to the car for beer. Stay with her. Keep her warm.
Right hand to God, Dr. D.



What exactly does this expression mean?



Answer



"I swear/promise."


It's common practice in the US to place one's hand on a Bible and/or raise one's right hand when making an oath, such as being sworn into office (like the president) or when testifying in court.


You may also hear "God as my witness" or "May God smite me."


Friday, February 21, 2020

game design - Factors to consider when building an algorithm for gun recoil


What would be a good algorithm for calculating the recoil of a shooting guns cross-hairs?


What I've got now, is something like this:



  1. Define min/max recoil based on weapon size

  2. Generate random number of "delta" movement

  3. Apply random value to X, Y, or both of cross-hairs (only "up" on the Y axis)

  4. Multiply new delta based on time from the previous shot (more recoil for full-auto)


What I'm worried about is that this feels rather predicable, what other factors should one take into account when building recoil? While I'd like it to be somewhat predictable, I'd also like to keep players on their toes. I'm thinking about increasing the min/max recoil values by a large amount (relatively) and adding a weighting, so large recoils will be more rare -- it seems like a lot of effort to go into something I felt would be simple.



Maybe this is just something that needs to be fine-tuned with additional playtesting, and more playtesters? I think that it's important to note, that the recoil will be a large part of the game, and is a key factor in the game being fun/challenging or not.



Answer



Guns tend to recoil vertically far more than they recoil to the left or right (at least the few I've fired -- pistols and a shotgun -- have done so to the best of my recollection). I have a feeling the random variance in X would just feel unusual.


I would start with an implementation that kicks the gun/view upwards only, probably based on the power of the gun. When fired, a cooldown timer starts. If the gun is fired again while the cooldown timer is still counting down, the vertical kick is applied again, with intensity proportional to how much time is left on the timer. After a certain threshold it might be appropriate to add X axis variance to indicate that the player is really losing control of the (probably automatic) weapon. I've never fired such a thing so I don't know what that is supposed to feel like, but I imagine "chaotic" would fit nicely. The cooldown should probably scale a bit -- but nonlinearly -- as you continue to fire and the intensity of the kicks should probably be similarly damped or smoothed. Pure linear measures might feel too harsh.


Whatever you do, it sounds like your initial plans called for a fair bit of randomization and I don't think that would be appropriate -- a small bit, certainly, but sudden large recoils amidst smaller ones seem like they'd be unusual.


difference - You look good vs You are looking good


I have been told that 'you look good' is the perfect compliment to give. Because 'you are looking good' is not colloquial. How correct is it?


For example, if I have to ask others about myself:



  1. How do I look?

  2. How am I looking? (This would be incorrect I guess)


Having said that, I've come across 'you're looking good / nice' kind of dialogues in English movies.


How to differentiate the uses of both?




present perfect - Using "recently" with past simple



Is it fine to use recently with the past simple tense in the following sentence?



Did you read any books recently?



Is it grammatically correct?


Or do I have to use:



Have you read any books recently?





Thursday, February 20, 2020

grammar - How to explain repeating words for different subjects


Suppose I have numbers, letters and names. Suppose further that I would like to store them in matrices, a matrix for each. Then, how could I explain this in a correct English sentence?



The numbers, the letters and the names are stored in their own matrices, a matrix for each.



Is this correct?



Answer



The numbers, letters and names are each stored in their own separate matrix.


or



The numbers, letters, and names are each stored in a separate matrix.


word usage - Is it possible to use 'shall' for intentions? is PEU wrong here?


M.swan PEU (3rd edition-unit:217) says,



" Topic: announcing decisions: will

We often use will when we tell people about a decision as we make it.for instant if we're agreeing to do something.
               e.g:1. OK. we'll buy the tickets.
                      2.The phone's ringing. I'll answer it.

Shall is not used in this way.
               e.g:You can have it for $50. -OK.I'll buy it. (NOT: I shall buy it) "





According to this, we can't use shall (with first persons) for intentions or decisions which made at the time of speaking.but the book 'Cambridge Grammar Of English' and these web seits( 1 , 2 ) say that shall can be used to announce intentions or decisions. for example,



  • I don't want anyone with me.I shall do this on my own. (reference:CGE)

  • I shall contact you again when I have further information.


So my questions is, is it possible to use shall for intentions or decisions as we make them(with I&we)? [if the answer is Yes ,Why do PEU say "shall is not used for decisions "]


I searched on the internet and read lot of grammar book but I could not find a clear answer to this confusion.so any answer is appreciated.




Wednesday, February 19, 2020

graphics - How can I easily create cloud texture maps?


I am making 3d planets in my game; these will be viewed as "globes". Some of them will need cloud layers. I looked at various Blender tutorials for creating "earth", and for their cloud layers they use earth cloud maps from NASA.


However I will be creating a fictional universe with many procedurally-generated planets. So I would like to use many variations.


I'm hoping there's a way to procedurally generate cloud maps such as the NASA link. I will also need to create gas giants, so I will also need other kinds of cloud texture maps.


If that is too difficult, I could fall back to creating several variations of cloud maps. For example, 3 for earth-like, 3 for gas giants, etc.



So how do I statically create or programmatically generate such cloud maps?



Answer



Cloud generation is fun! I'll cover both offline and runtime methods.


Pre-rendered clouds


If you want to pre-render your cloud textures offline, look no further than Photoshop (or Gimp, if you prefer). Both programs can easily generate cloud patterns. Menu items tend to move around between releases, but as of Gimp 2.8.2 the core command you're looking for is Filters -> Render -> Clouds -> Solid Noise. You'll need to create a new blank image before the command is enabled. I encourage you to experiment with the noise parameters, but just as one example, here's what happens if you set "Random Seed" to 1, "Detail" to 4, "X Size" to 4.0, "Y Size" to 8.0, disable "Randomize" and "Turbulent", and enable "Tilable": Raw output of Gimp


One further step I definitely recommend is editing the image's levels (Colors -> Levels... in Gimp). By dragging the endpoints around, you can effectively change the level of cloud cover from "fully overcast" to "not a cloud in the sky". Thresholded clouds


Other interesting possibilities:



  • Use the "Dodge" and "Burn" tools to manually brighten/darken portions of the image.

  • Warp the cloud image to suggest wind patterns. Try Gimp's Filters -> Distorts -> Whirl and Pinch... command, or for more control use Filters -> Distorts -> IWarp... with the Deform Mode set to "Swirl". Keep it subtle, though -- too much warping tends to blur the high-frequency detail out of the image.


  • Add multiple independent cloud layers to simulate different types of clouds, from thin and wispy to big & chunky (I'm sure they have proper scientific names, but damnit Jim, I'm a programmer, not a meteorologist!). In this case, you'd probably want to save each layer as a separate image so you can animate them independently at runtime.


It really depends on your artistic vision. Go nuts! When you're finished, remember to export the texture as a single-channel grayscale image, so you can use the same cloud data for your color and alpha channel at runtime.


Runtime cloud generation


Generating unlimited cloud patterns at runtime is a bit more involved, but still totally feasible. It's a huge topic, and this will only cover the broad strokes.


Basically you're going to replicate Gimp's "Solid Noise" command in your shader code, using a noise function like the canonical Perlin Noise to generate infinite, smooth, deterministic, (optionally) periodic noise volumes. Your question didn't specify which rendering API you're targeting, so I can't get too specific here; chapter 26 of "GPU Gems 2" covers a variant of Perlin noise in (somewhat dated) HLSL and CgFX, or you can use this drop-in GLSL noise function. By sampling a 2D slice of a 3D noise volume, you get something like the Gimp "Solid Noise" command with Detail=0. The lower the distance between your noise volume samples, the lower-frequency ("smoother") your noise will be. To increase the level of high-frequency detail, start with a base low-frequency noise pattern and add additional higher-frequency "octaves" of noise, where each "octave" is a different slice of the 3D noise volume with a larger sampling distance and lower amplitude. A visual example of this process (which I found by Googling "multi-octave Perlin noise") can be found here.


As a huge added bonus, cloud textures generated in this fashion can very easily be animated! Add a time-based offset to your 3D noise function sample coordinates, and you'll get extremely convincing cloud motion (as seen in this video, for example). This is because the noise function is smooth in all three dimensions; scrolling the texture in the U/V direction causes the clouds to move around the planet, while scrolling in the W (perpendicular) direction has the effect of slowly "evolving" the clouds.


Warping clouds at runtime is possible as well, for hurricane-like effects. Results can actually be much higher quality than the naïve Gimp warp filters, which (as mentioned earlier) can lead to an overly blurry texture. One technique you definitely want to look into is "flow maps", as described by Alex Vlachos of Valve (SIGGRAPH 2010 slides) or Carlos Gonzalez of Naughty Dog (GDC 2012 slides). The basic idea is that you paint a vector field (the "flow map") and use it to distort and scroll the cloud texture at runtime, while periodically cross-fading between two different cloud textures when the distortion distance gets too high.


Which method to use?


Pre-rendering cloud textures in Gimp/Photoshop is extremely easy; you can generate a new texture in a few seconds once you get the hang of it. The runtime code is trivial, and very fast. However, more unique cloud textures means higher disk space requirements (also, a larger/slower download) and more VRAM usage at runtime.



Runtime cloud generation is much more difficult at first, but once you get it working it has several clear advantages over pre-rendered cloud textures. You can generate an infinite variety of realistic animated cloud patterns without using any additional disk space or VRAM. However, the runtime cost of evaluating multiple 3D noise functions per-pixel can be steep; your cloud pixel shaders will be much slower than they in the pre-rendered case.


TL;DR: definitely start by using pre-rendered clouds, and switch to runtime procedural clouds if you need the extra variety (or want an extra programming challenge).


plural forms - Should I write "all the data is correct" or "all the data are correct"?


Which sentence is correct:



In this section you can make a payment: verify carefully that all the data submitted is correct and confirm by clicking the Proceed button.



or



In this section you can make a payment: verify carefully that all the data submitted are correct and confirm by clicking the Proceed button.




Answer




Answer: either form is fine.


Data is typically treated in contemporary English as a "mass noun", an undifferentiated collection (like "sand") that takes the singular "is".


This is the most common usage today.


But it CAN also be treated as a plural of "datum" and take "are" with equal ease and correctness.


If we recast the sentence with an explicit plural noun: "In this section you can make a payment: verify carefully that all the answers submitted ARE correct and confirm by clicking the Proceed button." then you must use "are".


If there was prior discussion of "data items" or the like, then the established context may cause the plural treatment to be preferred for continuity.


c# - What designs are there for a component based entity system that are user friendly but still flexible?


I've been interested in the component based entity system for a while, and read countless articles on it (The Insomiac games, the pretty standard Evolve Your Hierarchy, the T-Machine, Chronoclast ... just to name a few).


They all seem to have a structure on the outside of something like:


Entity e = Entity.Create();
e.AddComponent(RenderComponent, ...);
//do lots of stuff
e.GetComponent(...).SetPos(4, 5, 6);


And if you bring in the idea of shared data (this is the best design I've seen so far, in terms of not duplicating data everywhere)


e.GetProperty("Name").Value = "blah";

Yes, this is very efficient. However, it isn't exactly the easiest to read or write; it feels very clunky and working-against-you.


I personally would like to do something like:


e.SetPosition(4, 5, 6);
e.Name = "Blah";

Though of course the only way to get to that kind of design is back in the Entity->NPC->Enemy->FlyingEnemy->FlyingEnemyWithAHatOn kind of hierarchy this design tries to avoid.


Has anyone seen a design for this kind of component system which is still flexible, yet maintains a level of user friendliness? And for that matter, manages to get around the (probably the hardest problem) data storage in a good way?



What designs are there for a component based entity system that are user friendly but still flexible?



Answer



One of the things that Unity does is provide some helper accessors on the parent game object to provide a more user friendly access to common components.


For example, you might have your position stored in a Transform component. Using your example you would have to write something like


e.GetComponent().position = new Vector3( whatever );

But in Unity, that gets simplified to


e.transform.position = ....;

Where transform is literally just a simple helper method in the base GameObject class (Entity class in your case) that does



Transform transform
{
get { return this.GetComponent(); }
}

Unity also does a few other things, like setting a "Name" property on the game object itself instead of in its child components.


Personally I don't like the idea of your shared-data-by-name design. Accessing properties by name instead of by a variable and having the user also have to know what type it is just seems really error prone to me. What Unity does is that they use similar methods as the GameObject transform property within the Component classes to access sibling components. So any arbitrary component you write can simply do this:


var myPos = this.transform.position;

To access the position. Where that transform property does something like this



Transform transform
{
get { return this.gameObject.GetComponent(); }
}

Sure, it's a little more verbose than just saying e.position = whatever, but you get used to it, and it doesn't look as nasty as the generic properties. And yes, you would have to do it the roundabout way for your client components, but the idea is that all your common "engine" components (renderers, colliders, audio sources, transforms, etc) have the easy accessors.


unity - How to access UI elements in a canvas in UnityUI


I am looking for elements on a canvas (a textfield and a slider); so I can retrieve values and pass them to a function.


But so far I can't figure out how to access them; I can see the methods of the canvas itself, but I can't see the name of the elements that I did add on the canvas.


I have the canvas saved in a variable which is public; then I did place a slider and textfield, connected to text labels; but I can't seem to access neither the label nor the slider or textfield.



Canvas --
|___ Text
| |_____ InputField
|
|___ Text
|_____ Slider

I did plan to access to the text value in the input field doing something like canvas.text.inputfield.text, but this does not work, since I can't see the name of the text field when using dot notation. Same goes for the slider.


public Canvas mainmenu;


void Start() {
mainmenu = mainmenu.Getomponent();
}

public RetrieveData(){
// dot notation does not find sub elements of mainmenu canvas
// only the properties and methods of the canvas itself.
}

How do you actually access elements on a UI canvas, if you can't see them directly, even if they are parented to other elements?





negation - How to answer a negative question in English?



Q: "Don't you know?"




If I really don't know, how should I respond to this question? Yes or No?


There's a similar question on EL&U, but the answer isn't clear how it works:



Also here on ELU too:



These answers are confusing. I want to know what one word answer I can use. In other words I want to know:




  • What will native speakers understand if I reply No to this question?





  • What will native speakers understand if I reply Yes to this question?






tower defense - What is grid in Unity and how can I implement it?



I'm a beginner. I need to place a grid on my map in Unity and would like to access it to place a simple object on mouse click. How can I achieve this ?


I am unable to understand the grid functionality, should I have to write code for a 2D array or is there something in Unity that I can access, and what is basically the grid like something when I click my background image ?



Answer



This could be achieved in many ways. Unity has a pretty advanced positioning system as it is.


For just regular positioning look here https://docs.unity3d.com/Manual/PositioningGameObjects.html


But without prior knowledge of whether you are looking to do this in code, it's hard to give a good answer. Try asking more specific, precise questions that you feel others could benefit from that can't be found out with a little bit of research


EDIT: ADDITION This shows how to place a tower, the towers positions are checked against in an arraylist is C#. Hopefully this should give you an idea of how to start.


public GameObject tower;
public GameObject tower2;
private ArrayList towerList = new ArrayList();

void Start()
{
Vector3 towerPosition = new Vector3(1.0F, .75F, 1.0F);
foreach (GameObject towerObject in towerList)
{
if (towerObject.transform.position == towerPosition)
{
// there is already a tower in that position
return;
}

}

tower = (GameObject)Instantiate(tower, new Vector3(1.0F, .75F, 1.0F), this.transform.rotation);
towerList.Add(tower);

// for proof of concept you we're going to try to place the tower
// in the same position as the other one
Vector3 towerPosition2 = new Vector3(1.0F, .75F, 1.0F);
foreach (GameObject towerObject in towerList)
{

if (towerObject.transform.position == towerPosition2)
{
// there is already a tower in that position
return;
}
}
tower2 = (GameObject)Instantiate(tower2, new Vector3(1.0F, .75F, 1.0F), this.transform.rotation);
towerList.Add(tower2);
}

pronouns - "Without his telling me" vs. "Without him telling me"?


I was reading a book and encountered this sentence (emphasis added by me):




  1. I know it without his telling me.



Despite being grammatically correct, it seemed a little strange to me. What came to my mind was this sentence instead:





  1. I know it without him telling me.



Another case was this:




  1. I can’t control the fact of temptation, but there’s no chance of my giving in to it.




QUESTION: Is using "me" here in #3 (or "him" as done in the previous one) correct? If so, what's the difference between the two?



Answer




The OP clarified that he/she wanted to know the semantic difference between these two phrases. I will maintain that, for the general reader, both sentences are generally considered acceptable, and the semantics are identical for practically all purposes. There are some subtle variations in style or meaning in which one form might be better than another.


My position is supported by an absolutely outstanding work, with an unassuming name, General properties of Gerunds, Participles and Verbal Nouns (PDF). Based on this work, the phrase "his telling me" seems to be more traditionally (perhaps prescriptively) correct. Also, "him telling me" has more of a feel of an independent clause (aka IP), "subject verb object", while "his telling me" is more like a dependent clause (aka DP). The author also indicates there is ambiguity in how to parse these. Don't hesitate to search the General properties of Gerunds, Participles and Verbal Nouns for semantics to find additional relevant information.


I want to highlight this work (and the author) and encourage an interested linguistics reader to investigate further. It's a very interesting (advanced yet sometimes very readable) exposition on many facets of this complex issue, including this exact issue of semantics. The above chapter seems to contain (directly or indirectly via reference) the best research on the theory to this question through the publication date.


For reference, the above text is part of a book (also with an unassuming name), Complementation in English: A Minimalist Approach (Cornilescu 2003, Google Ref) I must say Alexandra Cornilescu has many outstanding and intriguing papers/books that I'll be reading. Here's the Wikipedia Page (translated) about him.
General searches to find these works, see:



I haven't the time to dig further into this at this point. Anyone else is free to use the source I've provided to create/enhance their own answer.





The following is my entire answer before the above note was created, and I still stand by it's value.



For the grammar involved, this question has a very good answer in https://english.stackexchange.com/a/2628/61171 (Credit @CopperKettle for reference.) I'll attempt to convey my native AmEng intuition with examples so we can avoid some of the heavier grammar lingo.


Second, let's simplify by giving him a name, "John". Now we can talk about John directly. This is simply a teaching aid.


Semantics


In isolation, there's no significant semantic difference between the two sentences. They are saying exactly the same thing in slightly different ways.


But in some contexts, the differences could have some differing semantic pull. The issue of semantic differences might be rephrased: If you polled 100 people, what meanings would be interpreted, and what would be the percentage of each meaning?


Grammar Basics


Let's review some basic grammar.





  • he and him are pronouns that can be replaced with "John".



    • I saw John.

    • I saw him.

    • John saw me.

    • He saw me.





  • his is a possessive pronoun and can be replaced with John's:



    • John's bike is green.

    • His bike is green.

    • I saw John's bike.

    • I saw his bike.





Now consider some gerunds in which their function is more clear than the OP's sentences:



  • I saw John dancing.

  • I saw him dancing. (I saw him doing something. This conveys a sense of action.)

  • John's dancing is beautiful.

  • His dancing is beautiful. ("His dancing" is the subject. I'm talking about his act of dancing, as if it were a static thing.)


Note in the last example, "His dancing" is the subject of the sentence and functions like a noun.




FIRST SENTENCE



For the first sentence, his is a possessive pronoun, and "his telling me" functions as a noun. The following sentences all have a similar feel to them (relative to the "him" sentence):



  • I know it without his telling me.

  • I know it without John's act of telling me.

  • I know it without John's advice.

  • I know it without advice.


Here's a tree showing a traditional grammar layout of the sentence:1


enter image description here


Here's a more modern syntax tree:2

enter image description here


SECOND SENTENCE


In the second sentence, the word "him" is the same as "John". Note the following:



  • John told Paul a secret.

  • He told him a secret.


Now consider the following:



  • It's funny to see John dancing.



"John dancing" has an active meaning. John is hypothetically doing something. Here's a modern syntax tree:3


enter image description here




Footnotes on Syntax Trees


This section demonstrates how to easily create the images contained within this answer. As such, this section is only ancillary technical information and is separate from the answer proper.


Below, I show how to generate Labeled Bracket Notation and how to render that notation into an image of a tree.


For the modern grammar syntax trees, I went to the the Stanford Parser and entered the first sentence. I substituted [ for ( and ] for ) and plugged that into http://yohasebe.com/rsyntaxtree. That gave a pretty picture. I usually resize these in something like pixlr to make them smaller. These trees use artificial intelligence natural language processing (NLP), and as such, may give less-than-ideal or incorrect results.


1. Sentence 1 - Traditional Grammar


The first sentence I changed to typify a traditional grammar.




[S_Traditional-Grammar
[Subject I]
[Predicate
[Verb-"know"
[Object it]
[PP
[PRP without]
[NP
[N-POS his]

[NP
[GER-PH^ telling me]
]
]
]
]
]
]

2. Sentence 1 - Modern Syntax Tree



The Stanford Parser results for the modern syntax tree didn't express what I wanted, so I modified it slightly.



[S
[NP [PRP I]]
[VP [VBP know]
[NP [PRP it]]
[PP [IN without]
[NP his telling me]
]
]

]

3. Sentence 2 - Modern Syntax Tree


For the second sentence, I liked the Stanford Parser result. It's still slightly simplified.



[ROOT
[S
[NP [PRP I]]
[VP [VBP know]
[NP [PRP it]]

[PP [IN without]
[S
[NP [PRP him]]
[VP [VBG telling]
[NP [PRP me]]]]]]
]]

contractions - Why don't we contract "it is" in "If it is, then..."


I wrote some instructions for a friend today, asking them to check something, and then act differently depending on the result:



It should be spinning when it's on. If it isn't then check the batteries. If it is then replace the frobulator.




I used the contraction "it's" for the first sentence to replace "it is".


I didn't use the contraction for the second because I chose to contract "is not" to "isn't". However I could have chosen the opposite: "If it's not check the batteries" would have been fine.


However, the third sentence doesn't sound right if I contract "it is". "If it's then replace the frobulator" seems incorrect.


Is there a rule that explains why "it is" shouldn't be contracted in this case, or am I wrong, and that contraction would be fine in that last sentence?



Answer



From The Cambridge Grammar of the English Language, p.1614:



Prepositions, auxiliaries, and infinitival to are stressed when they are the sole or final element in a phrase-level constituent, a PP or VP [preposition phrase or verb phrase].



Note that be is always an auxiliary verb. In your example, is is an auxiliary at the end of a verb phrase:




1a. If it is ___ then replace the frobulator.
1b. *If it's ___ then replace the frobulator.   ← ungrammatical



If we added the ellipted word spinning back in, it would no longer be at the end of the phrase, and it would be possible to contract it:



2a. If it is spinning then replace the frobulator.
2b. If it's spinning then replace the frobulator.



This is the same reason you can't reduce it is to it's at the end of a sentence. Is needs to bear stress, so it can't be reduced to clitic form (can't be contracted).





In this answer, the * symbol means that a sentence is ungrammatical.


gerunds - Why so many –ing nouns (present participles) do not take the definite article “the”?


For example we do not say:



I look forward to the seeing you, or in the doing so.




But sometimes we say:



In the beginning, in the fighting, the ruling, etc.



As such, is there any different rule concerning the –ing nouns or they should follow the same rules as the common nouns do?



Answer



'seeing' is not a noun there. It's a verb. And due to 'look forward...' pattern, it takes the verb in the form of '-ing'.



I look forward to see seeing you.




Does the question still stand?


pyglet - How can I distribute a native executable for a Python program?


Lately all of my work has been in Python (and Ruby), and I'm in love with those two languages. There are many libraries for game development on Python but the problem I see is that many of those frameworks don't cover the "distribution" aspect of game creation. I'd like to code my game on Python (and any other pure Python extra libraries I need) and be able to distribute an executable for the main PC platforms (Windows, Mac and Linux).


Any options out there or what are the best combinations for this? (maybe pyglet + cx_freeze)




Tuesday, February 18, 2020

c++ - Interactions between game objects


I'm programming a basic Pacman clone to teach myself game programming. However, I'm struggling with the best way to have the game objects communicate/interact without my code becoming a huge mess.


Right now, I have a stack (implemented as a list) of objects in my base Game class. These objects include components such as Graphics, Input, etc. as well as "actual objects" such as Map, Pacman, etc. While running the game, the Game class loops through all of the objects and updates the ones which want to be updated and draws the ones which want to be drawn.


However, these objects must obviously interact. I implemented a Link function on the objects which allows one object to be "linked" to another; i.e. it gives one class a pointer to the other class so interaction can take place. For example, the Pacman class may use Link to be given a pointer to the Map class so Pacman can determine whether or not it can move in a certain direction.


With a game as simple as Pacman, this structure probably won't be too challenging to maintain, but were a game to have many interacting objects, I suspect the code would get out of hand. Is the method I am using right now alright, or should I look at another implementation of object communication? If so, what would you recommend?



I've looked at Communication between objects in games?, but whenever I try to implement the mediator pattern, I end up with a giant mediator class which is a challenge to maintain. Is the mediator pattern what I should be using?




plural forms - Why is "aircrafts" bad English, while "crafts" is okay?


I am puzzled by this. Why is "aircrafts" invalid, while "crafts" can be used legitimately? I've also heard that "crafts" cannot be used because the plural of "craft" is always "craft". Which is right?



Answer



"Craft" is one of those words that has several very different meanings.



"Craft" could mean "skilled work" or "hobby". In this case, the plural is "crafts" - such as in "arts and crafts".


"Craft" can also mean a vehicle that people use to travel through water, air, or outer space. In this case, the plural is "craft" (no 's') - such as in "aircraft", "watercraft", or "spacecraft".


Here's an explanation for why this is:



Use for "small boat" is first recorded 1670s, probably from a phrase similar to vessels of small craft and referring either to the trade they did or the seamanship they required, or perhaps it preserves the word in its original sense of "power."



Source: Online Etymology Dictionary, Craft


So, it sounds like we have the British Navy to thank for this confusing usage.


interpretation - Ellipsis with apostrophe?


This is a strophe from one song:



"But the times were hard, Lord,
the jobs were few
all through Tecumseh valley
but she asked around
and a job she found
tending bar at Gypsy Sally's"




Can I rewrite that this way:


"tending bar at Gypsy Sally's bar"



Answer



Whilst you can never be too sure with song lyrics - since they're open to multiple interpretations - I think this use of the possessive s ('s) is a common trait in place names of businesses, particularly bars or public houses.



They serve a good beer at Gypsy Sally's (bar).



It is also used to imply "home", when used after an individual's name or family name.



I'm just going over to the Johnsons' (house).




Additionally, this is often true of professions such as: the butcher's or the baker's.


So, in short, you can rewrite the last line like that, in order to understand it, but it doesn't flow so well because of the repetition of bar. As such, I wouldn't rewrite it that way.


phrasal verbs - What is the difference between 'run off' and 'run away'?


Both run away and run off mean escape, but is there any difference?



Answer



Run away means you put distance between yourself and the unpleasant thing. It doesn't say whether your escape was successful. It doesn't say whether you're coming back. It doesn't say whether anyone will catch up with you.


Run off means you went somewhere that you cannot be effectively retrieved either because you went someplace hard to reach or because no one knows where you went. It usually implies that you're not coming back. "Run off" can almost always be changed to "run away" without making a statement false.


A specific use of "run away" is actually closer to the meaning of "run off", and that is when a child or teenager runs away from their parents for a long period of time (days, months, years or permanently). The child or teenager is said to be "running away from home" and is referred to as a "runaway".


http://www.merriam-webster.com/dictionary/run%20off gives another usage of "run off".
Run off can refer to causing someone else to run off.




  • "I ran off the intruder by chasing him and throwing rocks at him".

  • "The intruder ran off when I chased him and threw rocks at him".


Both sentence are good and mean pretty much the same thing.


Have any video game designs used non-uniform random numbers in interesting ways?


A variety of video games use uniformly distributed numbers to decide the outcome of an event, such as a "50% chance to hit" almost always means to check if a random floating point number from 0-1 is greater than 0.5. Many games will layer a few of these uniform percentages on top of each other, for instance a D&D hit roll is a uniformly distributed number from 1-20, except that 1 and 20 have special outcomes. To my mind it seems like things like critical hits are added by designers to try and emulate the fact that in reality hitting/missing or winning/losing is not actually a binary outcome.


In many cases the real life amount of "damage" done by an attack would likely be closer to a gaussian/bell curve distribution, which many results in the middle but the occasional very exciting outlier and smooth curve connecting them. Dice games like Settlers of Catan emulate gaussian distributions by adding together multiple independent rolls, but I feel like I've almost never seen this mechanic in video games.


It seems like games like Civilization (Sid Meier talked extensively at GDC about player perception not matching the actual math used in the game) would benefit from results that matched how things work in the real world. Have any video games used a gaussian or otherwise non-uniform distribution of random numbers in interesting ways?



Answer



Shooters often use Gaussian random distribution for weapon accuracy. (If you use linear random numbers and you have bullet decals, it's very easy for a player to see that the accuracy distribution is square, which "feels wrong.")


One interesting random selection method that you don't mention, but which shows up fairly often in games, is "random without replacement." This is analogous to drawing cards from a deck; the game runs in random order through a set of possible outcomes (put together with the desired distribution) and then "reshuffles." This is done to reduce the chance of lucky or unlucky streaks.


question marks - How to use "to be" at the end of a sentence


I have some confusion about this; for example:



Where is the bank?



I don't know where the bank is.



I don't know how to be is used at the end of sentences.



Answer



Let's start with a basic sentence:



The bank is there.



We can turn this into a wh-question by replacing there with where:




The bank is where? (inappropriate in most circumstances)



This kind of question is acceptable in a few limited circumstances, but most wh-questions have two additional things done to them:




  1. wh-fronting. We move where to the front of the sentence:



    Where the bank is ____? (inappropriate in most circumstances)



    It leaves behind a gap, which I've marked with a blank (____). (The gap is usually not written.) The word where and the gap refer to the same thing. What's important is this: you can't add a complement after is because there's a gap there.



    "Where the bank is?" is only appropriate in a few limited circumstances, like if you're repeating something back to someone. It's usually incorrect. To fix it, we need to do one more thing:




  2. Subject-auxiliary inversion. The subject (the bank) and the auxiliary verb (is) switch places:



    Where is the bank ____?



    Subject-auxiliary inversion marks a sentence as a direct question. With both wh-fronting and subject-auxiliary inversion, we've created a complete question ("Where is the bank?").





However, if you want to use "where the bank is" as an indirect question, you don't switch the subject and auxiliary:



[ where the bank is ____ ]



This is a relative clause. It doesn't work as a direct question, which means it doesn't work as a sentence on its own. That's why I didn't capitalize where or put a period at the end. But it does work as an indirect question, as part of a larger declarative sentence:



I don't know [ where the bank is ____ ].



In this example, we've fronted where, but we did not invert the subject and auxiliary. That would be ungrammatical because it's not a direct question:




*I don't know [ where is the bank ____ ]. (ungrammatical)



(Technically, there are circumstances where it's possible to embed a direct question, particularly in speech. But I'm ignoring that here.)


Monday, February 17, 2020

grammar - Can "all" be used with both singular & plural verbs?


Are both sentences below correct? 1. All of the books are expensive. 2. All of the books is expensive.




python - What library for octrees or kd-trees?



Are there any robust performant libraries for indexing objects?


Objects would have bounds themselves, rather than being represented by points; and an object could therefore be in more than one compartment if the index divides things in fixed sized partitions.


It would need frustum culling and visiting objects hit by a ray as well as neighbourhood searches.


I can find lots of articles showing the math for the component parts, often as algebra rather than simple C, but nothing that puts it all together (apart from perhaps Ogre, although apparently PyOrge doesn't expose the octree). Surely hobby game makers don't all have to make their own spartial indices?


(I am sitting down writing my own sphere-sphere, sphere-ray, ray-aabb, cone-aabb, cone-fustrum, aabb-fustrum and octree implementation; surely there is a better way i.e. someone has already done this and make a nice package?!?!)


(Python or C/C++ w/bindings preferred)



Answer





Surely hobby game makers don't all have to make their own octrees?



Unless they are using something larger (like Ogre, or another physics/rendering engine), many do. An octree is a fairly simple structure to implement, and there's a lot of tradeoffs:



  • Is the octree intrusive or not? If it's intrusive you get better cache performance, but larger structures.

  • If it's not intrusive, does it store pointers or some kind of safe handle?

  • Is it stored flat or with child pointers?

  • How type-safe is it? If it uses templates, it'll be a lot safer with minimal runtime overhead, but much harder to bind to Python.

  • Any octree with spatial querying is going to have to include some kind of vector/point/ray type, and anything with frustum culling is going to include a frustum and matrix math routines. Is writing the code to interface that to the dozen matrix/vector classes you've already dragged in from all the other libraries you're using actually less work than just writing the base octree you want?

  • Is it thread-safe?



That being said, there are plenty of octree implementations online. Just don't assume grabbing one of them is going to save you much work, and don't assume there's One True Way to make any data structure other than an array.


java - How can I change this isometric engine to make it so that you could distinguish between blocks that are on different planes?


I have been working on an isometric minecraft-esque game engine for a strategy game I plan on making. As you can see, it really needs some sort of shading. It is difficult to distinguish between separate elevations when the camera is facing away from the slope because everything is the same shade. So my question is: can I shade just a specific section of a sprite? All of those blocks are just sprites, so if I shaded the entire image, it would shade the whole block. I am using LWJGL. Are there any other approaches to take?


Here is a screenshot from the engine: http://i44.tinypic.com/qxqlix.jpg




Answer



One possible solution would be drawing edges along where the terrain changes height in dark black. So, the effect generated would look like height lines.


design patterns - In some games, we just let the main() loop be the Player object or Table object?


I was thinking that let's say if there is a game of Blackjack or MasterMind, then we should have a class called Dealer or ComputerPal, which is how the computer interact with us (as a dealer for Blackjack or as the person giving hints for MasterMind).


And then there should be a Player object, and the way to play one game is


aPlayer.playGame


but I noticed that a book was just using the main() loop to act as the player (or as the Controller of the game), calling the Dealer methods to dealer the cards, ask for player's action, etc...


1) Is this just a lazy way to model all the proper objects?


2) If more objects are to be added, who should call the aDealer.dealCards and then ask for aPlayer.askForAction? (because it is strange to let the Player handle all the logical steps). Should there be a Table object that handle all these logic and then to play one round of game, use aTable.playGame? What is a good object design for such game?




infinitives - When is "seems to be" used instead of "seems"?



  1. The baby seems happy/comfortable.

  2. The baby seems to be happy/comfortable.


Are these both correct? If both are correct, what are the differences between them?




Sunday, February 16, 2020

possessives - The name of the boy vs.The boy's name


Which one is correct or are both correct?



The boy's name is nice.
The name of the boy is nice.



I'm really confused these two sentences? Which one is more suitable?



Answer



"The name of the boy" and "the boy's name" are both grammatical, and in many contexts have the same meaning. But not all. ("The name of boy" is not grammatical).



In most contexts, even formal or literary ones, we would say "The boy's name" rather than "the name of the boy".


So "The boy's name is Michael" is quite normal, and "The name of the boy is Michael" is a bit unusual, but perfectly understandable and grammatical.


But, oddly, your example doesn't quite work: "The boy's name is nice" is fine, but "The name of the boy is nice" sounds very odd to me. I can't quite define why, I'm afraid: I just expect "The name of the boy is" to be followed by the name, and nothing else.


phrase usage - how to use "call on" phrasal verb


which one of those two sentences is correct



"The professor called on me for question 1"




or



"The professor called me on for question 1"





Saturday, February 15, 2020

phrase usage - How to “apologize for the inconvenience” customer and invite to restaurant again - in the most short way?



How to say apologize for the inconvenience customer and invite to restaurant again - in the most short way?


It looks that in English I should say that I am apologize (for something). So we apologize and invite again is invalid and should be we apologize for the inconvenience and invite again??? In Polish is not to be specific you just "apologize" not need to say "for what" it is optional


Consider such case - restaurant has some emergency and you want politely ask customer to come again?


How it will say native speaker in short (not what build long sentences but pass message).


What phrase will use he/she?




C# Design for Ability System


I'm a novice programmer but I have completed a pre-university in web prog so I am not a total noob. I'm using Unity, but this is just C# for now.



This is my first big project and I need some professional insight to make sure the design is not flawed. Currently working on abilities in an turn based rpg game.


What you might need to know: Abilities need to be learned/chosen, they may have requirements(levels, weapontype, more/etc.) New abilities will be added to the game with updates.


This is still the primitive stage, but very important to me because this project is more about learning to do it right rather than just getting it done.


Here are the following classes where we create abilities:


public abstract class Ability {
public readonly int id, multi, manaCost;

public Ability(int id, int multi, int manaCost) {
this.id = id;
this.multi = multi;

this.manaCost = manaCost;
}
public virtual void resolve(Actor user, Actor target){}
//Would create more methods with different parameters based on different abilities
//Example for multi target ability
public virtual void resolve(Actor user, Actor[] targets){}
}

Pretty simple stuff, Actor is just a in-game character. resolve is where the ability effects will be coded


using UnityEngine;

public class Freeze : Ability {
public Freeze() : base(0, 0, 3) { }

public override void resolve(Actor user, Actor target) {
int damage = 2 * user.attribute[2];
Debug.Log (damage);
target.damage(damage);

/*System.Random rnd = new System.Random();
if(rnd.Next(100) <= 35)

target.state = new Frozen();*/
}
}

the way I was planning to use abilities is, in the main script of the battle system there would be an array that has all the abilities such as this:


Ability[] all_ability;
public void createAbilities(){
all_ability = new Ability[2]; //size increased as we create more abilities
all_ability[0] = new Freeze();
all_ability[1] = new FirstStrike(); //and so on as we create more

}

The index of the array is also the id of the ability which allows us to easily access abilities.


So if an Actor wanted to use freeze, the id of freeze would be stored in Actor i.e. p1.actors[0].ability_ids array


so let's say i've got what ability the player chose, it would be something like this


int aId = p1.actors[i].ability_ids[j]; //would return 0 assuming he chose freeze
all_ability[aId].resolve(p1.actors[i], p2.actors[k]);

Everything works so far, no errors, and damage gets calculated correctly but this is a very simple ability and still much more to add like damage counters, animations, status effects etc.


What should I look out for? is there a much easier way to do this I dont know about? I guess my main concern is, as we learn in web programming, it is said to be very bad to hard code values and everything should come from databases, but, is that also true for a game since each ability can be quite different? As you can see, everything is hard coded here. I guess I just want tips on things I may have done wrong/if there is a clear better way to do this. Thanks for any and all replies!




Answer



You sound like you're off to a good start! However, you asked a pretty general question, so I can only really offer some general pointers that might help!


To start with, I'd use a List instead of an array ( using System.Collections.Generic). You can still do abilityList[index] like with arrays, but you get the added benefit of not having to handle resizing if you run out of rooms (since it's handled by the List class), and LINQ queries, if you're into that!


After that, you should make sure your Actor has an "AddAbilities" method. Then, on load (or creation), you can simply go down the list, adding the abilities appropriately (instead of hardcoding them). For instance, if your character load data for Darth Vader is:


Force Lightning, Force Choke


(Not knowing how you intend to store stuff, let's just assume you somehow parse out a list of strings)


foreach(string abil in savedCharAbilities)
{
//You can use reflection or an AbilityFactory that takes a string parameter to create
// an instnace of the class based on it's name.

// If you have an enumeration of all of the possible abilities
// (only do this if you have a small total amount!), you could set up a switch statement
// to get your new Ability instead.

character.AddAbility(createdAbility);
}

Finally, you may also want to look into making your abilities MonoBehaviors that implement an Ability Interface instead of inheriting from an abstract class - that way you can make use of Unity's built in Enable properties (for toggle-able abilties), it's Update method (for quickly changing effects), and Unity's Invoke call (which calls the passed method X seconds later, or every X seconds if you call InvokePeriodic).


grammar - "Stopped talking" and "stopped to talk"


picture of a practice exercise


In this exercise:




Ali stopped _____ to his friend. He talked to him then.
a) talk
b) talking (I chose this one)
c) to talk (This one is marked as the correct answer)
d) being talked



Why did they choose "to talk" as the right answer? And why not "talking"?


I understand the meanings of talk and stop so I don't understand why one is wrong and the other correct.




Friday, February 14, 2020

textures - Algorithm for approximating sihlouette image as polygon






Possible Duplicate:
Is there any heuristic to polygonize a closed 2D raster shape with n triangles?



I want to be able to analyze a texture in real time and approximate a polygon to represent a silhouette. Imagine a person standing in front of a green screen and I want to approximately trace around their outline and get a 2D polygon as the result. Are there algorithms to do this and are they fast enough to work frame-to-frame in a game?


(I have found algorithms to triangulate polygons, but I am having trouble knowing what to search for that describes my goal.)




usage - Are there solutions to know which verbs are followed by the infinitive or the gerund?



I can know some patterns like these.




I enjoy cooking.


He wants to swim.



But for other verbs like admit, allow, agree, appear and so on. It seems that I have to remember which verbs are followed by infinitives or gerund.


I know I have to listen a lot. At least I know how to use "can't help" from this song "but I can't help falling in love with you...."


But for learner do we have only to remember them or are there any other solutions?




grammaticality - Gerunds:Having+past participle and being+past participle


Here are two sentences:




My having been to South-Korea helped me learn the languages when I took the classes.


Being accepted to Harvard university was the greatest day of my life.



Is it common or natural way to write such 'having+past participle' and being+past participle construction in formal writing? Or should I use the other alternatives for these? Are these construction encouraged in writing? And What about in spoken English? Thanks.


source http://www.myenglishteacher.net/gerunds.html



Answer



The two examples which the OP cited are formal, the first being very formal; and both are in the passive voice.


If I were to recast the two examples into the active voice, I would suggest the following:





  1. My having been to South-Korea helped me learn the languages when I took the classes.



    • The time I spent in South-Korea helped me learn the languages …




  2. Being accepted to Harvard university was the greatest day of my life.



    • The time Harvard University accepted my application, was the greatest day of my life





Note that Harvard University is capitalised, because it is the full and complete name of the institution.





  • Is the use of gerund + past participle common in formal writing?


It is still used in formal writing but it is, without a shadow of a doubt, becoming less common in speech. If it's used sparingly in an essay, an English teacher might be favourably impressed but if the student resorts to using this type of construction whenever possible, it will sound at best antiquated and, at worst, pompous.


Some people maintain that the passive voice should be used whenever it is required, while others claim an overuse of the passive voice actually presents poor style.



Supporters of Strunk and White's The Elements of Style (1918) will say: “Use definite, specific, concrete language”, The active voice is usually more direct and vigorous than the passive:, and The habitual use of the active voice, however, makes for forcible writing. This is true not only in narrative principally concerned with action, but in writing of any kind.


In the end, choose the construction which you feel most confident with.


P.S Not all the examples of “tame sentences” cited by S&W are actually in the passive voice, and none begin with the gerund + past participle, just thought I'd warn you.


unity - Can I clip a collection of geometry to render only inside a particular worldspace volume?


I am making a VR app in Unity. I have a giant map that I want to display on a virtual table. The map is too large to fit on the table, and I cannot change its size. (It is a third party asset, and does not easily have that capability.)


How can I tell the camera not to render the parts of the map that fall off of the table? Perhaps something along the lines of:


Camera.DoNotRender(new Vector3(100, 0, 0));

I have been looking into using some MonoBehaviour messages such as OnPreRender, OnRenderObject, etc. But I do not know which one can help me, if any. Ideally, the pixels behind the non-rendered pixels should be rendered, but that is not my priority.


The map is made up of 100s of little renderers:



enter image description here


How can I have my Camera not render specific world space pixels?



Answer



One way to do this is with the clip function in a shader, which aborts rendering of a pixel if it fails a particular condition.


This lets you create custom-shaped clipping regions, but it has a downside: by the time you reach the clip test, most of the work of rasterizing the object is already done, so you end up paying a significant amount for the invisible portions of the model that don't actually get drawn in the end.


Be sure to profile this to determine whether it's an issue in your particular application - it might not be. If it is, there are some additional tricks you can use with depth, stencil, and off-screen buffers to exclude some of the redundant geometry.




Edit: a neat trick I've just learned is if you introduce a NaN or infinity into a vertex position, you can abort rendering of triangles using that vertex. So this can let you do some of this clipping per-vertex instead of solely per fragment, saving some rasterization costs.


v.vertex.x /= step(outOfBounds, 0.1f);


You need a margin like that 0.1f there that's bigger than your typical triangle - otherwise you can have a vertex outside your clipping margin abort a whole triangle that's partly inside the clipping volume.


Note that this doesn't seem to be an officially documented feature, just something GPUs tend to do 'cause how else are they going to render that triangle? ;)




Here's an example shader using this approach - use something like this on your map material to achieve the clipping:


Shader "Custom/ClipVolume" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0


// Expose parameters for the minimum x, minimum z,
// maximum x, and maximum z of the rendered volume.
_Corners ("Min XZ / Max XZ", Vector) = (-1, -1, 1, 1)
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200

// Allow back sides of the object to render.

Cull Off

CGPROGRAM

#pragma surface surf Standard fullforwardshadows
#pragma target 3.0

sampler2D _MainTex;

struct Input {

float2 uv_MainTex;
float3 worldPos;
};

half _Glossiness;
half _Metallic;
fixed4 _Color;

// Read the min xz/ max xz material properties.
float4 _Corners;


void surf (Input IN, inout SurfaceOutputStandard o) {

// Calculate a signed distance from the clipping volume.
float2 offset;
offset = IN.worldPos.xz - _Corners.zw;
float outOfBounds = max(offset.x, offset.y);
offset = _Corners.xy - IN.worldPos.xz;
outOfBounds = max(outOfBounds, max(offset.x, offset.y));
// Reject fragments that are outside the clipping volume.

clip(-outOfBounds);

// Default surface shading.
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG

}
// Note that the non-clipped Diffuse material will be used for shadows.
// If you need correct shadowing with clipped material, add a shadow pass
// that includes the same clipping logic as above.
FallBack "Diffuse"
}

Here's what it looks like on Unity's "Ethan" model:


Example of using the shader above to clip a character mesh


And here it is using the triangle aborting trick above to remove some of the excess geometry outside the clipping volume:



Example showing cropping of the underlying geometry


Entity/Component based engine rendering separation from logic


I noticed in Unity3D that each gameObject(entity) have its own renderer component, as far I understand, such component handle rendering logic.


I wonder if it is a common practice in entity/component based engines, when single entity have renderer components and logic components such as position, behavior altogether in one box?



Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.


With such approach it is impossible to swap renderers, it would require to rewrite all that customized renderers.


The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.


Is such approach somehow wrong?



Answer




Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.



In some entity systems, components only contain logic. In others, they only contain data. In yet others, they contain both. I'd certainly argue that putting the actual render commands (as in the OpenGL or D3D code) into the rendering component isn't ideal (see my answer here regarding the question "should objects render themselves?", which is the same principle under discussion). However, it is certainly possible to do so and even to do so in a fashion that allows the implementation of the rendering components to be swapped without having to alter the consumers of the component system. Doing so just involves any typical implementation-hiding technique.


It's acceptable, and common, to have a "visual component" that contains a reference to some renderable object that comes from the lower-level rendering subsystem and have that component export behavior or interface to allow the appearance data to be specified by other components (such as ones containing scripts).




The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite. Then some entity with Camera component would store all references to object that is visible to the camera. And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.


Is such approach somehow wrong?



I don't really see what you gain by having a "camera" component. It seems like a very heavyweight operation inject into the entity system. Does, for example, the presence of the camera component mean that you always get a scene rendered from that camera's perspective? How then do you determine which of those scenes to present to the user, and where? It feels like -- without knowing more about this design -- you'd be shoving a lot of unrelated responsibility into the camera component. I'd prefer to see that responsibility handled by something external to the entity system.


Otherwise, that sounds like a perfectly usable system. It will have it's pros and cons, of course, but those will become apparent in practice and many of them will be specific to your needs and/or the needs of your game.


Collision Resolution


I know quite well how to check for collisions, but I don't know how to handle the collision in a good way.


Simplified, if two objects collide I use some calculations to change the velocity direction. If I don't move the two objects they will still overlap and if the velocity is not big enough they will still collide after next update. This can cause objects to get stuck in each other.


But what if I try to move the two objects so they do not overlap. This sounds like a good idea but I have realised that if there is more than two objects this becomes very complicated. What if I move the two objects and one of them collides with other objects so I have to move them too and they may collide with walls etc.


I have a top down 2D game in mind but I don't think that has much to do with it. How are collisions usually handled?


This question is asked on behalf of Wooh




Answer



Daniel Kodicek covers this topic in great detail in his book, Mathematics & Physics for Programmers.


Kodicek does two things to achieve natural-looking collision resolution:



  • His collision detection function calculates the exact time two objects will collide.

  • He recalculates new velocities at the time of collision, so objects never overlap.


I uploaded a demo based on Kodicek's collision detection and resolution.


update: Here's a collision detection & resolution algorithm that is very similar to Kodicek's method. With source code. I still recommend Kodicek's book, as his algorithm is implemented slightly differently and much more thoroughly explained.


Thursday, February 13, 2020

java - Maintaining velocity of free fall body using Box2D in libGDX


I want to maintain the speed of a free-falling Box2D body using LibGDX. I'd like the vertical velocity increase with the level. I've applied a linear impulse and velocity actually increases like this:



fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);

I think this is a bad approach, because the speed has increased only a little and I applied as much as -800 units of impulse.


Below is my render function of game play screen class:


    public void render(float delta) {

Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

// camera.update();

// batch.setProjectionMatrix(camera.combined);
batch.begin();

backgroundSprite.draw(batch);
grassSprite.draw(batch);

// bucketSprite.draw(batch);

Iterator bodies = world.getBodies();


while(bodies.hasNext()){

Body body = bodies.next();

if(body.getUserData() != null){

String spriteName = (String) body.getUserData();

Sprite sprite = (Sprite) userDataMap.get(spriteName);


if(spriteName.equals("bucket"))
sprite.setPosition(body.getPosition().x + 345, body.getPosition().y + 230);
else
sprite.setPosition(body.getPosition().x + 375, body.getPosition().y + 225);

sprite.draw(batch);

}
}


batch.end();

fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);
// debugRenderer.render(world, camera.combined);
world.step(1/60f, 8, 3);
// world.clearForces();
}

My world is:


world = new World(new Vector2(0, -10), true);


Orthographic camera:


camera = new OrthographicCamera(800, 480);

My fruitBody fixture def is:


bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(0, 100);

// shape
CircleShape ballShape = new CircleShape();

ballShape.setRadius(15f);

//fixture
fixtureDef.friction = .1f;
fixtureDef.restitution = .7f;
fixtureDef.shape = ballShape;
fixtureDef.density = .2f;

fruitBody = world.createBody(bodyDef);
// fruitBody.setUserData(fruitSprite);

fruitBody.setUserData("fruit");
fruitBody.createFixture(fixtureDef);

I just want to increase the fruit's speed (free falling body) at each level by a given value.



Answer



Disclaimer: I have not used libgdx or Java before, this answer borrows syntax from the question and official documentation, and the code is untested


To make the bodies 'fall' under the influence of gravity in box2d, you must first pass a non-zero gravity vector to the b2World when constructing the world


World world = new World(new Vector2(0, -10), true);

This means that every time World::step is called the gravitational force will be applied to every DynamicBody and the velocity will be updated accordingly.




This is all well and good if all you want is constant acceleration, without any opposing forces. To add a little realism we would like to add a drag force to simulate air resistance. I know there are a lot of resources out there explaining how air drag works, and the wikipedia article is the obvious starting point.


In a nutshell, the magnitude of the drag force is most frequently modelled like this:


Drag Force


Whenever you encounter a new formula like this, I find the best way to get an understanding of it is to see what happens when specific variables are set to zero, become negative, or take on large values.


In this case I just want to consider what happens to the drag force when the velocity, v, changes and all other parameters are set to positive, real values.



  • If v -> 0 then Fd will also tend to zero.

  • If v >> 0 then Fd will take on a large positive value.

  • If v << 0 then Fd will take on a large positive value.



Notice Fd will never be negative. This is an important feature.


The direction of the drag force is frequently assumed to be opposite to the velocity vector. This is a simple assumption that is easy to implement and unconditionally stable in code.


So if our fruit is falling (accelerating) under the influence of gravity it's gaining speed. But while that's happening the drag force must be increasing because the velocity magnitude is increasing. The drag force will continue to increase until terminal velocity is reached.


Terminal velocity is the point at which the drag force is equal in magnitude and opposite in direction to the gravity force. If the forces are equal, the acceleration of the fruit must be zero, and the velocity of the fruit which satisfies this condition is the terminal velocity.


You can even determine what the terminal velocity must be at the outset if you set Fd = Fg and solve for v.


Implementation


This is great in theory, but how can we implement this in code?


box2d does not provide any built-in features to implement drag, so we have to do it ourselves.


To do this we need to get all the bodies and cycle through them at each time step, calling Body::applyForceToCenter on each one. I'm going to borrow the code from your rendering function as an example.



Iterator bodies = world.getBodies();

//This constant H is the lump constant of 1/2*rho*Cd*A from the wikipedia formula
//Play with this parameter to get the results you want
float H = 0.5;

while(bodies.hasNext()){

Body body = bodies.next();


Vector2 v = body.getLinearVelocity();

//Get the square of the velocity by computing the square of the distance from the origin
float vSqrd = v.dst2(Vector2());

//Calculate the magnitude of the drag force
float fMag = H*vSqrd;

//Calculate the drag force vector to apply
//We do this by taking the norm of the velocity and negating it to get the direction.

//That vector is multiplied by the magnitude to get the drag force we want to apply
Vector2 fd = -v.norm()*fMag;

//Finally we communicate this to box2d by calling applyForceToCenter
body.applyForceToCenter(fd);

}

That should be it. I don't have anything setup right now to run that code, but that is the is the general idea. I judged from your language that you were having more trouble understanding the physics than the code, which is why I expounded on that first.


As a side note applying linear impulses at every time step can produce some funky results because it applies the same impulse regardless of the timestep size (which can vary) whereas applying a force takes into account the timestep size.



algorithm - Space nebula cloud generation?


I found a cool kickstarter project called "Skywanders". It's an minecraft like space game with a lego like building system and pretty cool graphics.


One thing I noticed are the "nebula clouds". They are procedurally generated 3D Objects and they look amazing.


enter image description here


How do I generate such nebulas? I bet there's a way to do that. And is it possible to convert a 2D nebula into a 3D one? I didn't found any algorithm yet or other sources.



Answer



I've done something similar in the past through glsl's Fragment Shaders:



Nebula with Stars


https://www.shadertoy.com/view/lsyfWy


And a Processing version:


https://github.com/felipunky/Stars


It is basically a Fractional Brownian Motion or several layers of noise at different frequencies and amplitudes stacked together:


#define HASHSCALE .1031
// We create the pseudo-random number generator.
// https://www.shadertoy.com/view/4djSRW
float hash(float p)
{


vec3 p3 = fract(vec3(p) * HASHSCALE);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);

}

// This function is by @Inigo Quilez.
// We create the 3D noise by generating pseudo-random numbers in the x, y and z directions and then interpolating between them.
float noise( in vec3 x )

{

vec3 p = floor( x );
vec3 k = fract( x );

k *= k * k * ( 3.0 - 2.0 * k );

float n = p.x + p.y * 57.0 + p.z * 113.0;

float a = hash( n );

float b = hash( n + 1.0 );
float c = hash( n + 57.0 );
float d = hash( n + 58.0 );

float e = hash( n + 113.0 );
float f = hash( n + 114.0 );
float g = hash( n + 170.0 );
float h = hash( n + 171.0 );

float res = mix( mix( mix ( a, b, k.x ), mix( c, d, k.x ), k.y ),

mix( mix ( e, f, k.x ), mix( g, h, k.x ), k.y ),
k.z
);

return res;

}

// Here we do the stacking of noise at different octaves.
float fbm( in vec3 p )

{

float f = 0.0;
f += 0.5000 * noise( p ); p *= 2.02; p -= iTime * 0.5;
f += 0.2500 * noise( p ); p *= 2.03; p += iTime * 0.4;
f += 0.1250 * noise( p ); p *= 2.01; p -= iTime * 0.5;
f += 0.0625 * noise( p );
f += 0.0125 * noise( p );
return f / 0.9375;


}

I find this fbm function more readable and easier to tweak:


float fbm( in vec3 p )
{

float res = 0.0, fre = 1.0, amp = 1.0, div = 0.0;

for( int i = 0; i < 5; ++i )
{


res += amp * noise( p * fre );
div += amp;
amp *= 0.7;
fre *= 1.7;

}

res /= div;


return res;

}

Rendered through a Sphere Tracing Algorithm that accumulates for a volumetric look:


// This is our ray marching algorithm.
float ray( vec3 ro, vec3 rd, out float den )
{

float t = 0.0, maxD = 0.0, d = 1.0; den = 0.0;


// The more STEPS the more accurate the marching.
for( int i = 0; i < STEPS; ++i )
{

// Here we compute our Position p by the formula RayOrigin + RayDirection * our RayMarchStep.
vec3 p = ro + rd * t;

// This is our density, it is simply calling the Fractional Brownian Motion fbm function.
den = fbm( p );


// This allows us to put a limit in our accumulation of density.
maxD = maxD < den ? den : maxD;

// Here we bail on our marching according to MaximumDensity or our FAR threshold.
if( maxD > 1.0 || t > FAR ) break;

// We increment our RayMarchingSteps.
t += 0.05;


}

den = maxD;

return t;

}

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