Friday, January 31, 2020

planning - Essentials for building a RTS




I was wondering if anyone had any links to good reads or books in regards to things to think about when developing a RTS game, I would have been reading things like this and this but would like to read more into it.


Also I have development experience and soon would like to start building the skeleton myself but if anyone has any additional articles about the process (not in programming, but more on planning) that would be great help.



Answer



You could read some Gamasutra features. That's usually a good source of information, from people that actually ship games:



complementation - Is "A Star Shoots" a complete sentence?



A star shoots.



I read something like this somewhere. Can this be thought of as a complete sentence? How does one analyze this, grammatically? It looks as though it is missing some phrase. On the other hand we do say shooting star, so it isn't very clear if this is a complete sentence or not.


So, it may seem like a complete sentence? I guess, “A man runs.” and “It bites.”, seem like this, too? Same with: "A twig swayed.", "A ball rolls.", "A man jumps."




ellipsis - Some clarifications are needed about the grammar of Elliptical Structure


As far as I know, one application of elliptical structure is the omission from a clause one or more elements which has been repeated in previous clauses. However, I do not know whether there exists some specific general rule stating how and when to apply this structure.


Let me be more specific:






  1. Is it correct to say that one can always omit any word which has been repeated before?




  2. Is this structure optional (I have read somewhere that sometimes it is obligatory, for example with cases of comparative deletion (for example, the sentence “More students were in the class today than were there yesterday”), but I also have read somewhere that the omitted words can be added without producing an ungrammatical structure)?





I want to emphasize that I want to know the answer to my question for formal English used in academic writing.





Updated


After pondering the useful comments, I conclude that one should not consider any omission of words as ellipsis. In fact, ellipsis is the omission of elements which are understood in the context of the remaining elements and recoverable from the linguistic context. So examples such as “seeing more examples and gaining more experience” and “making more effort and reading more grammar textbooks” cannot be considered as elliptical structures since the second more is not recoverable from the linguistic context (We would have two sentences with different meaning before and after the omission of the second more).


So I think the first question should be rephrased as follows.



1’. Which repeated elements of a sentence can be omitted in order to get an elliptical structure?





Thursday, January 30, 2020

missing commas between coordinate adjectives?




to reach a mutually-agreed long-term comprehensive solution that would ensure IranĖˆs nuclear program will be exclusively peaceful.



As I see, in the noun phrase a mutually-agreed long-term comprehensive solution, all the three adjectives describing the head noun are coordinate. Then, shouldn't there be commas between them making it look like a mutually-agreed, long-term,/and comprehensive solution? Is putting a comma between coordinate adjectives a must? If so, what has happened here?


Links for further study are most welcomed:)



Answer



There's a quick way to tell the difference between coordinate adjectives and cumulative adjectives. If you can rearrange the adjectives without changing the meaning of the phrase, you've got coordinate adjectives, and you must use commas. If you can't rearrange them without changing the meaning of the phrase, you've got cumulative adjectives, and you shouldn't use commas.


Grammar Girl has a convenient set of examples that I'll reproduce here:



Coordinate adjectives are adjectives in a row that each separately modify the noun that follows (1), as in “heavy, bulky box.” Both “heavy” and “bulky” modify “box.” You can even rearrange the adjectives and say, “bulky, heavy box.”




"Bulky, heavy box" and "heavy, bulky box" mean the same thing as each other: the box is both bulky and heavy.



In the phrase “exquisite custom houseboat,” “custom” modifies “houseboat”—they become a unit—and then “exquisite” modifies “custom houseboat.”



To say "exquisite custom houseboat" means that you want to buy a custom houseboat, and to make sure that it's exquisite. If you reversed them - "custom exquisite houseboat" - it would mean that your first thought is for buying an exquisite houseboat, and then also you want it to be custom.


That is what is happening in your sentence. The speakers don't just want to reach a solution that is comprehensive, long-term, and mutually-agreed. They want to reach:



  • a [comprehensive solution] that is long-term and mutually-agreed

  • a [long-term comprehensive solution] that is mutually-agreed


  • a [mutually-agreed long-term comprehensive solution]


I'm not sure if that way of breaking it down makes sense or not. Basically, what happens is the adjective closest to the noun sort of fuses with it to become one noun-unit that the other adjective describes. But then that happens again with the next adjective - it fuses with the adj-noun unit to become a superunit, which the third adjective finally describes.


So you don't need the commas because "long-term comprehensive solution" is one "unit", which "mutually-agreed" is describing. It's the same as how you don't need a comma in "the fuzzy green tennis ball" (or "the exquisite custom houseboat").


past tense - Present perfect simple for an unfinished action



I decided to walk back home. I had walked for about 200 meters when the storm began and I ran to the nearest cafe.



Would it be possible to use past perfect progressive since the walk was not completed?


A worksheet about this issue



Answer



First, what you have in your example is the past perfect (I had walked) not the present perfect (I have walked).


That said, yes, in this case, the past perfect progressive conveys basically the same meaning, and is arguably preferable.




I had been walking about 200 meters...



One small nuance is that in this particular case, the past perfect allows for the possibility that the speaker stopped walking after 200 meters, whereas the past perfect progressive sounds like they were walking at the moment the storm hit.


tense - Until I went to army, I (had been / used to be / was ) a introverted person. - which one is right?




Until I went into the army, I (had been / used to be / was ) an introverted person. And after I I finished army service, I became more confident.



I think all of these are possible.


As for had been, I'm referring to the state of me being introverted before the accident that happened in the past. So, I think I can use had been.


And at the same time I feel I can use used to be and was.. If I don't want to emphasize the time gap between two accident, I feel I don't need to use past perfect. So I think this problem depends on how I'm going to say something.


which one is preferable? and what is the difference?



Answer



The use of "had been" sounds a bit unnatural in the sentence. I think you should use either used to be or was as follows:


I used to be/was an introverted person until I went into/joined the army.


Wednesday, January 29, 2020

Collision response for 2D racing game


The title is fairly self-explanatory. I have a 2D racing game that utilizes per-pixel collision detection (the track is essentially two bitmaps, one for the graphics, one for collision data). The problem I'm running into is that I can't figure out how to implement the collision response. I can figure this out for situations where I have a box colliding with another box, but the fact that my objects can essentially be any shape has me stumped.


The one approach that I've had some success with is to just sample a couple of pixels near the pixels that collide, build vectors out of those and then take the cross product of that, but it fails in many scenarios. Plus, it just seems like overengineering. In fact, I'm about 103% sure that I'm just overthinking the whole problem.


Has anyone tackled this problem?




Answer



When you have a collision you should try to understand where the collision occurred, the involved forces, the consequences of the involved forces.


Simplest case (I can tink of):



  • The impact occurs in the frame the collision is detected (no compenetration)

  • The colliding objects are perfectly elastic (no energy loss due deformation)

  • The colliding object are disks (to be removed as soon as possible)


Under those circumstances there is conservation of total momentum and kinetic energy.


When a collision occours, there is a contact surface between the colliding bodies: they can exchange energy only through this surface; in other words the impact forces are always perpendicular to this surface.



The main conseguence to this is that you can decompone the kinetic energy vector in a radial component (perpendicular to the contact surface) and a tangential component (parallel to the contact surface) seeing that the tangential one stays the same.


Knowing the value for a component, we can consider the collision be monodimensional, restricted to the radial direction.


If we consider the second body to be still, we have some formulas for the velocity after the collision:


V1 after impact vs V1 before impact


V2 after impact vs V1 before impact


It is possible to compute the velocity after impact knowing the velocity before the impact for the radial coponent we needed. (the kinetic energy is ½·m·v²).


You can resolve the case where the second body is moving, by superimpose the collision effects (first-moving-second-still + first-still-second-moving) or by change the inertial reference to be linked to the second body before the impact; it is the same.




We can spice up the simulation by removing the geometric simplification.


First you need to compute the contact surface and to find the contat point. (I left the problem to you but you can consider to simplify the contat mode to colliding boxes)



With your contact surface you can compute the resulting kinetic energy vector - as explained before - but then? We have to "allocate" this energy because a rigid body can move and rotate and some energy is required to change linear or angular velocity.


To know around what point our body will rotate, we need to know the position for the center of mass: this can be precomputed since depends just by the object shape and mass distribution.


If you have a collision bitmap you can consider to sum up the position for each "on" pixel then divide for how many "on" pixel there are: this implies that the object has the same density in each point.


If you like you can use a graymap to store the density for each point: black for 0 density (body absence) and white for maximum density; by multiplying the position by the density, you can compute a weighted average: your center of mass


When you know the center of mass you need to know the moment of inertia: multiply the density of each point by the square of the distance from the center of mass and sum up.


Knowing the center of mass and the collision point, you can decompose the kinetic energy vector in a radial component (starting from collision point and pointing toward the center of mass) and a tangential component.


The radial component tells us how many impact enercy becomes kinetic energy, while the tangential component tells us how many impact enercy becomes rotational energy.


As well as the velocity is bounded to the kinetic energy so Et = ½mV², also the angular velocity is bounded to the rotational energy so Er = ½IĻ‰², where I is the moment of inertia and Ļ‰ the rotational velocity in radians per second.


Using those two formulas you can compute the velocity vector and the angular velocity to add to your body.


The last triky part is how to know if Ļ‰ has to be clock/counterclok wise, since you will ever get a positive value.



Let I be the impact point and M the center of mass point, compute d = C - I;


Let Er be the tangential component for the impact kinetic energy, compute cross product in 2D, this will give you a right-handed perpendicular vector.


Now compute d·E if positive the rotation is CW else CCW


possessives - "the police conspiracy" vs. "the police's conspiracy"





  • I am firmly convinced he is innocent and his accusation is the result of the police conspiracy.







  • I am firmly convinced he is innocent and his accusation is the result of the police's conspiracy.





Which sentence do you think is a better choice?



Answer



The question in the post is about possessive inflection and use of a compound word of noun-noun combination.



Genitive inflection or "'s" means possession/ownership/relationship/authorship or, to say it the other way round, one noun belongs to another noun for any, some or all of the above reasons. As



  • cat's tail

  • Lamb's essays.

  • police's conspiracy.


In answering a question on the preference between a possessive or a compound noun Roger Woodham in 'BBC Learning English' writes that the link between two nouns can be established either by using possessive form or compound nouns. As



  • The US Bank's Finance Division

  • The US Bank Finance Division



Both are possible, but sometimes one form is more likely than another. For example, complemental noun groups can often be rephrased as compounds without "'s".



  • the relativity theory.


  • the linguistics department.


    In a noun-noun combination of compound noun the first noun is more like a classifying adjective; it descrbes the nature of second noun. In news paper headlines or reports, such nouns summarize a lot of information at a stroke.




  • Watergate Scandal.





From the question it is not clear whether the police is the only perpetrator of the conspiracy or just a party to a multi-agency conspiracy which go by the name, Police Conspiracy.


If the police is only to blame for the conspiracy, POLICE'S CONSPIRACY has an edge over the other option. If we overlook niceties, both can do.


prepositions - What does 'of' mean in 'to be predicated of'?


I can't pinpoint why, but the OF in to be predicated OF has been bothering me. I read user John Lawler's comment, but still don't understand user TRomano's comment .


Please pinpoint which definition of OF matches the use in: to be predicated OF?
Please ensure to specify its number (as per ODO's enumeration of the many definitions).




android - LibGDX Swipe Detection Left and Right


I have displayed an image at the center of the screen with libgdx. If I swipe left, the image should move to the left; and, if I swipe right, image should move to the right.


Subsequent swipes to the left should move the image left. The same should happen for right. I used GestureListener.


It works to some extent in the sense if I swipe left first image moves left. But after that if I try to swipe right the image still moves left.


So how do I implement the expected behavior?


class MyGestureListener implements GestureListener {
@Override
public boolean fling(float velocityX, float velocityY, int button) {
if (velocityX>0)
iX += 20;

else
iX -= 20;
System.out.println("iX: "+iX);
return true;
}
}

// ...
Gdx.input.setInputProcessor(new GestureDetector(0.0f, 0.0f, 0.0f, 5f, new MyGestureListener()));


// ...
batch.draw(splashTexture, iX, iY);

Answer



There are a few potential problems here. Lets take a look at your code first:


if(arg0>0)
iX += 20;
else
iX-=20;

arg0 is the velocityX of the last known horizontal velocity of the finger in pixels per second. Here's the method signature for fling():




fling


boolean fling(float velocityX, float velocityY, int button)


Called when the user dragged a finger over the screen and lifted it. Reports the last known velocity of the finger in pixels per second.


 Parameters: 
velocityX - velocity on x in seconds
velocityY - velocity on y in seconds

So, the method is not taking in ALL the data of the swipe, it's merely taking the final position info. What happens if you ended your swipe without any horizontal velocity? According to your code, the answer would be, move left because the X velocity in the final position would be zero.


if(arg0>0)  

iX += 20;
else // This includes X == 0 because you only checked greater than!
iX-=20;

What happens if you swipe upwards? According to your code, the final position would be move left, because arg1 has the upwards movement and is being ignored. What happens if you swipe downwards? According to your code, the final position would be move left. What happens if you swipe a little to the right and a little to the left? Move left.


I think what you want to do instead is something along the following lines:


   @Override
public boolean fling(float velocityX, float velocityY, int button) {
if(Math.abs(velocityX)>Math.abs(velocityY)){
if(velocityX>0){

iX+=20;
}else if (velocityX<0){
iX-=20;
} else {
// Do nothing.
}
}else{

// Ignore the input, because we don't care about up/down swipes.
}

return true;
}

A few additional notes:




  • Debugging: For debugging, I recommend that you log not only the resulting iX, but also the incoming arg0 (velocityX) values. I strongly suspect that a few minutes of looking at the input data will resolve the issue. In particular, you're going to want to know if this method is receiving zero values (which with your code will move the image left), if it's receiving non-negative values when it should be receiving negative values, and so forth.




  • Set the MaxFlingDelay: A word about fling(): fling() is not always called. You need to set the maxFlingDelay in the GestureDetector constructor for the amount you want to trigger a fling(), otherwise it uses a default value, which you may not be happy with.





  • Consider Pan and Other Alternatives:Consider alternatives to fling() including pan(). As has been noted by Benjamin, you may want pan() instead (or something else). That's an excellent suggestion and possible solution.




  • Run a Gesture Detector Test: To help decide on whether to use fling() and to see if fling() is giving the right values, play around with this gesture detector test.




  • Consider the Return Boolean: When you return true in this method, you're signalling that the input has been handled and shouldn't be processed further. That's not descriptive of the code sample I gave you (where up/down flings are ignored, for example). You may want to modify it to put the proper return trues/return falses in the appropriate places, so you don't run into unexpected behavior later if you implement other touch handling for nearby entities.





  • Variable Names: This is just a minor pet-peeve. It makes things much easier to read if you use descriptive variable names (like velocityX, velocityY, above) instead of Arg0, Arg1, iX, and so on. You asked above why you received a downvote. Don't know why somebody gave it, but sometimes code with bad naming conventions rubs people the wrong way.




Tuesday, January 28, 2020

Should I put the article?


I have the following passage:



Prospects for the increasing of organic products sales volumes by agrarian enterprises depend on the improvement of the marketing product and assortment policy, (the) qualified pricing, (the) professional logistics and distribution, and the formation of the manufacturer's brand and its products.



I doubt about if I should use articles "the".




c++ - Spherical to Cartesian Coordinates


Well I'm reading the Frank's Luna DirectX10 book and, while I'm trying to understand the first demo, I found something that's not very clear at least for me. In the updateScene method, when I press A, S, W or D, the angles mTheta and mPhi change, but after that, there are three lines of code that I don't understand exactly what they do:


// Convert Spherical to Cartesian coordinates: mPhi measured from +y
// and mTheta measured counterclockwise from -z.
float x = 5.0f*sinf(mPhi)*sinf(mTheta);
float z = -5.0f*sinf(mPhi)*cosf(mTheta);
float y = 5.0f*cosf(mPhi);


I mean, this explains that they do, it says that it converts the spherical coordinates to cartesian coordinates, but, mathematically, why? why the x value is calculated by the product of the sins of both angles? And the z by the product of the sine and cosine? and why the y just uses the cosine? After that, those values (x, y and z) are used to build the view matrix.


The book doesn't explain (mathematically) why those values are calculated like that (and I didn't find anything to help me to understand it at the first Part of the book: "Mathematical prerequisites"), so it would be good if someone could explain me what exactly happen in those code lines or just give me a link that helps me to understand the math part.


Thanks in advance!




word choice - When should I use fatherland instead of motherland?


Is it politically correct to use either word (fatherland, motherland) to refer to the country of birth? Which one is more appropriate and when?





graphics - Making a 2D game with responsive resolution


I am making a 2D game, however I wish for it to be resolution agnostic.


My target resolution i.e. where things look as intended is 1600 x 900.


My ideas are:


Make the HUD stay fixed to the sides no matter what resolution, use different size for HUD graphics under a certain resolution and another under a certain large one.



Use large HD PNG sprites/backgrounds which are a power of 2, so they scale nicely. No vectors.


Use the player's native resolution. Scale the game area (not the HUD) to fit (resulting zooming in some and cropping the game area sides if necessary for widescreen, no stretch), but always fill the screen.


Have a min and max resolution limit for small and very large displays where you will just change the resolution(?) or scale up/down to fit.


What I am a bit confused though is what math formula I would use to scale the game area correctly based on the resolution no matter the aspect ratio, fully fit in a square screen and with some clip to the sides for widescreen.


Pseudocode would help as well. :)




grammatical number - "Who is Lisa friends with?" or "Who are Lisa friends with?"



Is it correct to ask



Who is Lisa friends with?



or should it be



Who are Lisa friends with?





usage of articles: definite article or zero article?




The Chinese invented the paper


The Chinese invented paper



I can't decide which article we get before paper — zero article or the.


Are we talking about paper in general (so zero article is used before it) or is the definite article the used?




Monday, January 27, 2020

legal - Are fonts covered by copyright?


I want to use the font Trajan Pro, but I'm not sure that it would be legal. I've read a bit on fonts and copyright, and the only thing I could get was it depends on the license and where it was copyrighted, and sometimes it isn't copyrighted at all.


So how would I tell if the font Trajan Pro, or any other font, is under copyright?



Answer



Fonts, like all forms of creative expression, are covered by copyright unless their copyright owner explicitly releases them into the public domain. Distributing a font, or derivative works of the font (bitmap images of text rendered using the font, for example) would be a violation of copyright, unless you have a license to do so.


The particular font you mention, Trajan Pro, was created by Carol Twomby. A license for this font (and several of her other fonts) can be purchased from Adobe.


According to the licensing terms, this font license gives permission to embed the font into an electronic document for the purposes of preview and print, but not for the font to be installable by any end-users of such a document. It does not explicitly grant the right to (for example) be baked into a texture page and used in a game, so it's not obvious whether even purchasing a license would allow you to legally use this font the way that you wish to. As usual for this sort of thing: consult a practising lawyer in your area for an authoritative answer of whether a game constitutes an "electronic document" for the purposes of this font license.


Similar discussions have been held on the official Adobe discussion forums a few years back, but never received an official reply from Adobe.



Sunday, January 26, 2020

java - Libgdx: How to setZIndex for pause dialog?


Pause dialog has to appear on top of the play screen, it has to appear on top of other objects.


I have tried to use


dialog.setZIndex(10); // or whatever number and I tried adding it in many places

It just doesn't work, how to make the dialog be on top of other objects? for a ccomplete version here


I'm using only one batch and the stage is used only to add background and dialog


  stage = new Stage();
Gdx.input.setInputProcessor(stage);
stage.addActor(bg); // somewhere else in the code

stage.addActor(btnPause);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
stage.act(delta);
stage.draw(); // and thats about it for stage
game.batch.begin();
font.setColor(Color.YELLOW);
font.draw(game.batch, myScore + score, Gdx.graphics.getWidth(), camY);
// and here I draw the game game.batch.draw(game) and I'm using only one batch


I hope I didn't miss anything


If I put the game batch in state.RUN in an effort to hide objects when the pause dialogue appears, then when I resume, it will go to batch.end and exit the game


Pause


public void pause() {
this.state = State.PAUSE;
final Dialog dialogP = new Dialog("", skin, "pauseDialog") {};

dialogP.setScale(4, 6);
dialogP.setPosition(Align.center, Gdx.graphics.getHeight());



dialogP.addAction(sequence(alpha(0),
parallel(fadeIn(.5 f)),
moveBy(0, -1000 f, .30 f, Interpolation.smooth),
moveBy(0, 30 f, .40 f, Interpolation.smooth)));

//PlayOn
ImageButton btnPlayOn = UIFactory.createButton(txtrPlayOn);
btnPlayOn.setSize(40, 40);
btnPlayOn.setPosition(75, 75, Align.center);

dialogP.addActor(btnPlayOn);

//EndGame
ImageButton btnEndGame = UIFactory.createButton(txtrEndGame);
btnEndGame.setSize(40, 40);
btnEndGame.setPosition(75, 55, Align.center);
dialogP.addActor(btnEndGame);

stage.addActor(dialogP);



//playOnAction
btnPlayOn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
dialogP.hide();
resume();
}
});



//EndGameAction
//PlayButtonAcion
btnEndGame.addListener(
new InputListener() {
@Override
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
super.enter(event, x, y, pointer, fromActor);

Actions.scaleTo(0.7 f, 0.7 f, 0.5 f, Interpolation.bounceOut);

stage.addAction(Actions.sequence(Actions.moveBy(-stage.getWidth(), 0, .5 f), Actions.run(new Runnable() {
@Override
public void run() {
game.setScreen(new MainMenuScreen(game));
}
})));

}

});



}

The basic principle is implemented from the accepted answer to this question




unity - Pushing an object on other colliders makes the pusher object go through


Screenshot of Game Scene



The Wall moves to the right and pushes the Character with it. The character travels along a bunch of Blocks with colliders attached to them.


This is the result:


Animated gif showing wall passing through character


At some point, the Character gets stuck and the Wall goes through the Character and comes out the other side.


I've tried to play around with the collision detection and other values of the rigidbodies. I tried to add a Physics material with no friction.


I am wondering what could cause this issue.


Here are the values of my GameObjects


Settings used on game objects




word usage - "exist" vs. "there are"


Which of the following sentences is more natural or normal, is there any difference?




  • Currently, there are powerful query languages for XML.

  • Currently, powerful query languages exist for XML.



What are the other alternatives?



Answer




Both seem natural to me. I'd use both without hesitating.



What are the other alternatives?



I actually can't think of any without making the sentence clumsy


It's possible to say:



Currently, there exist some powerful query languages for XML



but this sounds mathematical, sounding similar to "For every x, there exists a y such that..." so I wouldn't use it.



meaning - Does the sentence mean what it is meant to mean?



Happiness is about health of body and soul.



The sentence is intended to mean that "happiness is health of body and soul" or that "happiness consists in health of body and soul".


Does it mean so? Is "to be about" used in such sense?




word choice - "In" and "on": How can I decide which one to use for vehicles?


Examples:



  • In a car, van, etc.

  • On a bus, boat, motorcycle, etc.


How can one decide which preposition to use? Is memorization the only way or is there a better way?


Note: People generally explain this by either distinguishing between open and closed vehicles or between large and small vehicles. However, the examples I've given defeat both explanations.




usage - difference between "came along" and "along came"


What is the difference between the two?


For example





  1. John came along.

  2. Along came John.



I don't understand the difference in usage and yet I come across too many sentences starting with 'Along came'


Could you please explain how to understand this.




Saturday, January 25, 2020

android - Collision detection problems using AABB's


I implemented a simple collision detection routine using AABB's between my main game sprite and various platforms (Please see code below). It works great, but I'm now introducing gravity to make my character fall and it's shown up some problems with my CD routine.


I think the crux of the matter is that my CD routine moves the sprite back along the axis in which it has penetrated the least amount into the other sprite. So, if it's more in the Y axis than the X, then it will move it back along the X Axis.


However, now my (hero) sprite is now falling at a rate of 30 pixels per frame (It's a 1504 high screen - I need it to fall this fast as I want to try to simulate 'normal' gravity, any slower just look weird) I'm getting these issues. I will try to show what is happening (and what I think is causing it - although I'm not sure) with a few pictures: (Code below pictures).



I would appreciate some suggestions on how to get around this issue.


enter image description here


For clarification, in the above right picture, when I say the position is corrected 'incorrectly' that's maybe a bit misleading. The code itself is working correctly for how it is written, or put another way, the algorithm itself if behaving how I would expect it to, but I need to change it's behaviour to stop this problem happening, hope that clarifies my comments in the picture.


enter image description here


My Code


public boolean heroWithPlatforms(){

//Set Hero center for this frame
heroCenterX = hero.xScreen+(hero.quadWidth/2);
heroCenterY = hero.yScreen+(hero.quadHeight/2);


//Iterate through all platforms to check for collisions
for(x=0;x
//Set platform Center for this iteration
platformCenterX = platformCoords[x]+(platforms.quadWidth/2);
platformCenterY = platformCoords[x+1]+(platforms.quadHeight/2);

// the Dif variables are the difference (absolute value)
// of the center of the two sprites being compared (one for X axis difference

//and on for the Y axis difference)
difX = Math.abs(heroCenterX-platformCenterX);
difY = Math.abs(heroCenterY-platformCenterY);

//If 1
//Check the difference between the 2 centers and compare it to the vector (the sum of
//the two sprite's widths/2. If it is smaller, then the sprites are pverlapping along
//the X axis and we can now proceed to check the Y axis
if (difX

//If 2
//Same as above but for the Y axis, if this is also true, then we have a collision
if(difY //we now know sprites are colliding, so we now need to know exactly by how much
//penX will hold the value equal to the amount one sprite (hero, in this case)
//has overlapped with the other sprite (the platform)
penX = vecXPlatform-difX;
penY = vecYPlatform-difY;
//One sprite has penetrated into the other, mostly in the Y axis, so move sprite
//back on the X Axis

if (penX < penY){hero.xScreen-=penX*(heroCenterX-platformCenterX>=0 ? -1 : 1);}
//Sprite has penetrated into the other, mostly in the X asis, so move sprite
//back on the Y Axis
else if (penY < penX) {hero.yScreen-=penY*(heroCenterY-platformCenterY>=0 ? -1 : 1);}
return true;
}//Close 'If' 2
} //Close 'If' 1
}
//Otherwise, no collision


return false;
}

Answer



during my experiments with HTML5 canvas and AABB I found exactly what you are experiencing. This did happen when I attempted to make a platform from adjacent boxes of 32x32 pixels.


Solutions I attempted by order of my personal preference


1 - Divide movements by axis


My current one, and I think I will continue my game with it. But be sure to check what I call Phantom AABB if you need a quick solution without having to modify a lot your current design.


My game world has very simple physics. There is no concept of forces (yet), only displacement. Gravity is a constant displacement to down. No acceleration (yet).


Displacement are applied by axis. And in this consist this first solution.


Each game frame:



player.moves.y += gravity;
player.moves.x += move_x;

move_x is set according to input processing, if not arrow key pressed then move_x = 0. Vales below zero mean left, otherwise to the right.


Process all other moving sprites and decide the values of their "moves" component, they have the "moves" component too.


Note: after collision detection and response, the move component must be set to zero, both x and y properties, because the next tick the gravity will be added again. If you not reset, you will end with a moves.y of two times the desired gravity, and in the next tick it will be three times.


Then enter the displacement applying and collision detection code.


The moves component is not really the current position of the sprite. The sprite has not moved yet even if moves.x or y changed. The "moves" component is a way to save displacement to be applied to sprite position in the correct part of the game loop.


Process first the y axis (moves.y). Apply moves.y to sprite.position.y. Then apply AABB method to see if the moving sprite being processed is overlapping a platform AABB (you already understood how to do this). If it overlaps then move the sprite back in the y axis by applying penetration.y. Yes, as opposed to my other answer, now this move evolved method ignores the penetration.x, for this step of the process. And we use the penetration.y even if it is greater than penetration.x, we aren't even checking for it.


Then process the x axis (moves.x). Apply moves.x to sprite.position.x. And do the opposite than before. You will move the sprite only in the horizontal axis this time by applying penetration.x. As before, you don't care if penetration.x is less or greater than penetration.y.



The concept here, is that if the sprite is not moving, and was initially not colliding, then it will remain like that in the next frame (sprite.moves.x and y are zero). The special case where another game object magically teleports to a position that overlaps the sprite begin processed is something I will handle later.


When a sprite begin to move. If it moving only in the x axis, then we are only interested if it penetrates something by the left or the right. As the sprite is not moving down, and we know this because the y property of the moves component is zero, we don't even check the calculated value for the penetration.y, we only see at penetration.x. If penetration exist in the axis of movement, we apply correction, otherwise we simply let the sprite move.


What about diagonal displacement, not necessarily in a 45 degrees angle?


The proposed system can handle it. You only need to process each axis separately. During your simulation. Different forces are applied to the sprite. Even if your engine does not understand forces yet. These forces translates to an arbitrary displacement in the 2D plane, this displacement is a 2D vector in any direction and of any length. From this vector you can extract the y axis and the x axis.


What to do if the displacement vector is too large?


You don't want this:


|
|
|
|

|
|
|
|_ _ _ _ _ _ _ _ _

As our new moves applying logic process an axis first and then the other, a large displacement may end being saw by the collision code like a big L, this won't correctly detect collisions with objects that are intersecting your displacement vector.


The solution is to divide large displacements in small steps, ideally your sprite width or height, or half your sprite width or height. To obtain something like this:


|_
|_
|_

|_
|_
|_
|_
|_

What about teleporting sprites?


If you represent teleporting as a large displacement, using the same moves component as a normal move, then no problem. If you don't, then you have to think a way to mark the teleporting sprite to be processed by the collision code (adding to a list dedicated to this purpose?), during response code you can directly displace the standing sprite that was in the way when the teleportation occurred.


2 - Phantom AABB


Have a secondary AABB for each sprite affected by gravity that starts at the sprite bottom, has the same width of the sprite AABB, and 1 pixel height.



The idea here is that this phantom AABB is always colliding with the platform below the sprite. Only when this phantom AABB is not overlapping anything gravity is allowed to be applied to the sprite.


You don't need to calculate penetration vector for the phantom AABB and the platform. You only interested in a simple collision test, if it overlaps a platform, gravity cannot be applied. Your sprite can have a boolean property that tells if it is over a platform or in the air. You are in the air when your phantom AABB is not colliding with a platform below the player.


This:


player.position.y += gravity;

Becomes something like this:


if (player.onGround == false) player.position.y += gravity;

Very simple and reliably.


You leave your AABB implementation as is.



The phantom AABB may have a dedicated loop that process them, that only check for simple collisions, and do not waste time calculating the penetration vector. This loop must be before the normal collision and response code. You may apply gravity during this loop, for those sprites on the air apply gravity. If the phantom AABB is in itself a class or structure, it may have a reference to the sprite it belongs to.


This is very similar to the other proposed solution where you check if your player is jumping. I giving a possible way of detect if the player has its feet over a platform.


2d - How do I find the intersections between colliding circles?


I want to find whether 2 circles with radii r1 and r2 intersect, and if so, where they do so. Is there a simple solution?



Answer




Determining whether two circles intersect at all is fairly simple: we calculate whether the distance between their center points is less than or equal to the sum of their two radiuses.(note below)


Let's consider the two circles to be \$A\$ and \$B\$: we'll define their center points as vectors \$c_A\$ and \$c_B\$, and their radii as \$r_A\$ and \$r_B\$. The circles are colliding if:


$$ \tag{0} \lvert c_A - c_B \rvert \le r_A + r_B $$


... where \$\lvert this \rvert\$ represents a vector's magnitude (length).



Here's that equation represented as pseudocode:


class Circle {
center: Vector2
radius: Float
}

function Colliding(a: Circle, b: Circle) returns Boolean {
Vector2 diff = a.center - b.center
Float maxDistance = a.radius + b.radius
return diff.magnitude <= maxDistance

}

Note: We're counting the edges exactly touching—the distance being exactly the sum of the two radiuses—as a collision. If you don't want to count this as a collision then in the above formula and code sample, where they use \$\le\$ or <=, you should instead use \$<\$ or <.



(This section is heavy on mathematics. For code, skip to the next section.)


“Intersection of Two Circles” by Paul Bourke (1997) describes an algorithm for determining the exact intersection points. It provides this diagram:



In this diagram, \$P_0\$ and \$P_1\$ are the center points of the two circles, and \$r_0\$ and \$r_1\$ are their radii.


First we determine the distance (\$d\$) between the circles:


$$ \tag{1} d = \lvert P_1 - P_0 \rvert $$



Then we'll check a couple of potential cases which result in no intersections.


$$ \tag{2} \begin{array}{lll} \text{case 1:} & d > r_0 + r_1 \\ \text{case 2:} & d < \lVert r_0 - r_1 \rVert \; \text{or} \; d = 0 \end{array} $$



  • If case 1 is true, the circles are wholly separate and there is no edge intersection.

  • If case 2 is true, one circle wholly contains the other, and there is no edge intersection to calculate, or rather the intersection is 100% of the smallest circle. (Note we're subtracting not adding; \$\lVert this \rVert\$ represents absolute value.)


If neither is true, we'll proceed.


In that diagram, there are two triangles we can observe: one is \$P_0 P_2 P_3\$, which has \$r_0\$, \$a\$, and \$h\$ for its edges. The other is \$P_1 P_2 P_3\$ which has edges \$r_1\$, \$b\$, and \$h\$. We need to calculate \$P_2\$, \$a\$, and \$h\$, and then eventually we can work out \$P_3\$ which represents the intersection points we're looking for. We never use \$b\$ so we'll leave that aside.


First we'll calculate \$a\$:


$$ \tag{3} a = \frac{r_0^2 - r_1^2 + d^2}{2d} $$



Then \$h\$: $$ \tag{4} \begin{array}{rl} \text{given} & a^2 + h^2 = r_0^2, \\ \text{then} & h^2 = r_0^2 - a^2 \\ \text{therefore} & h = \sqrt{r_0^2 - a^2} \\ \end{array} $$


Then \$P_2\$:


$$ \tag{5} P_2 = P_0 + \frac {a(P_1 - P_0)}{d} $$


If the circles are exactly as far apart as our combined radiuses, \$P_2\$ is our single (only) collision point:


$$ \tag{6} \begin{array}{ll} \text{case 3:} & d = r_0 + r_1 \end{array} $$


If case 3 is true we just use \$P_2\$; done.


Otherwise we have two collision points, represented in the diagram as \$P_3\$. We'll calculate \$P_3\$ by its coordinates \$(x_3, y_3)\$. In the following, \$x_0\$/\$y_0\$ thru \$x_2\$/\$y_2\$ represent the x- and y-coords of \$P_0\$ thru \$P_2\$.


$$ \tag{7} \begin{align} x_3 &= x_2 \pm \frac{h(y_1 - y_0)}{d} \\ y_3 &= y_2 \mp \frac{h(x_1 - x_0)}{d} \end{align} $$


So, \$P_3\$ is actually two points, right? Let's call them \$\alpha\$ and \$\beta\$ (alpha and beta). We follow equation 7 to calculate them as follows:


$$ \tag{8} \text{for }\alpha\text{:} \\ \begin{align} x_\alpha &= x_2 + \frac{h(y_1 - y_0)}{d} \\ y_\alpha &= y_2 - \frac{h(x_1 - x_0)}{d} \end{align} $$



$$ \tag{9} \text{for }\beta\text{:} \\ \begin{align} x_\beta &= x_2 - \frac{h(y_1 - y_0)}{d} \\ y_\beta &= y_2 + \frac{h(x_1 - x_0)}{d} \end{align} $$


Note: plus and minus, then minus and plus.


Now we have our intersection points, \$\alpha\$ and \$\beta\$.



Here's the above algorithm as code, written in Python 2.7.


from math import sqrt

# Determines whether two circles collide and, if applicable,
# the points at which their borders intersect.
# Based on an algorithm described by Paul Bourke:

# https://web.archive.org/web/20060911063359/http://local.wasp.uwa.edu.au/~pbourke/geometry/2circle/
# Arguments:
# P0 (Vector2): the centre point of the first circle
# P1 (Vector2): the centre point of the second circle
# r0 (number): radius of the first circle
# r1 (number): radius of the second circle
# Returns:
# False if the circles do not collide
# True if one circle wholly contains another such that the borders
# do not overlap, or overlap exactly (e.g. two identical circles)

# An array of two vectors containing the intersection points
# if the circle's borders intersect.
def Intersection(P0, P1, r0, r1):
if type(P0) != Vector2 or type(P1) != Vector2:
raise TypeError("P0 and P1 must be vectors")

# equation 1
offset = P1 - P0
d = offset.magnitude()


# equation 2: simple cases
if d > (r0 + r1):
# no collision
return False
elif d == 0 or d < abs(r0 - r1):
# full containment
return True

# equation 3
a = (r0**2 - r1**2 + d**2) / (2 * d)


# equation 4
h = sqrt(r0**2 - a**2)

# equation 5
P2 = P0 + a * (P1 - P0) / d

# equation 6
if (d == r0 + r1):
return [P2]


# equation 8
alpha_x = P2.x + h * (P1.y - P0.y) / d
alpha_y = P2.y - h * (P1.x - P0.x) / d
alpha = Vector2(alpha_x, alpha_y)

# equation 9
beta_x = P2.x - h * (P1.y - P0.y) / d
beta_y = P2.y + h * (P1.x - P0.x) / d
beta = Vector2(beta_x, beta_y)


return [alpha, beta]



# Simple 2D vector class.
# Based on work by @mcleonard on github:
# https://gist.github.com/mcleonard/5351452
class Vector2(object):
def __init__(self, x, y):

"""Create a vector, e.g. v = Vector2(10, 15)"""
self.x = x
self.y = y

def magnitude(self):
"""Returns the magnitude of this vector."""
return sqrt(self.x**2 + self.y**2)

def __add__(self, other):
"""Returns the vector addition of self and other."""

newx = self.x + other.x
newy = self.y + other.y
return Vector2(newx, newy)

def __sub__(self, other):
"""Returns the vector difference of self and other."""
newx = self.x - other.x
newy = self.y - other.y
return Vector2(newx, newy)


def __mul__(self, other):
"""Multiplies each component if other is a scalar"""
if type (other) == type(1) or type(other) == type(1.0):
return Vector2(self.x * other, self.y * other)
else:
raise NotImplementedError

def __rmul__(self, other):
return self.__mul__(other)


def __div__(self, other):
"""Divides each component if other is a scalar"""
if type (other) == type(1) or type(other) == type(1.0):
return Vector2(self.x / other, self.y / other)
else:
raise NotImplementedError

def __str__(self):
"""Returns this vector as a string of the form: (x, y)"""
return "(%(x)d, %(y)d)" % { "x": self.x, "y": self.y }




def format(input):
if isinstance(input, list):
return "\n " + "\n ".join(str(v) for v in input)
else:
return "\n " + str(input)




def run_test(label, expected, actual):
print label
print "Expected:", format(expected)
print "Actual:", format(actual)
print "\n"



def run_all_tests():

run_test("Intersection 1", \
["(0.5, -1.93649)", "(0.5, 1.93649)"], \
Intersection(Vector2(0,0), Vector2(1, 0), 2, 2) \
)

run_test("Intersection 2", \
["(3.39254, -0.749778)", "(-1.99992, 3.02495)"], \
Intersection(Vector2(2, 3), Vector2(5.5, 8), 4, 9) \
)


run_test("Intersection 3", \
["(5.14024, 9.90651)", "(9.93669, 6.70888)"], \
Intersection(Vector2(8, 9), Vector2(4, 3), 3, 7) \
)

run_test("Single-point edge collision", \
["(2, 0)"], \
Intersection(Vector2(0,0), Vector2(4, 0), 2, 2) \
)


run_test("Wholly inside", \
"True", \
Intersection(Vector2(0,0), Vector2(1, 0), 5, 2) \
)

run_test("No collision", \
"False", \
Intersection(Vector2(0,0), Vector2(5, 0), 2, 2) \
)


run_test("The same circle twice", \
"True", \
Intersection(Vector2(0,0), Vector2(0,0), 5, 5) \
)

print "Expected values are approximations.\n"

run_all_tests()

Run this code on trinket.io here.



Some tests are defined at the bottom of the file. You can verify your results in Wolfram Alpha by running a query to determine the intersection of two circles like this:


intersection ((x - h)^2 + (y - k)^2 = r^2), ((x - h)^2 + (y - k)^2 = r^2)


Where for each of the two circles, h = x-coord, k = y-coord, and r = the radius.


Here's the Wolfram results for each of those intersection test cases:



Friday, January 24, 2020

difference - it VS. this Vs. that


Iv'e never understood what is the difference between the subject pronoun "it" and the demonstratives "this" and "that".


To be precise, I understand well the difference between those two demonstratives ("this" and "that"). "this" is used for when being close physically or when pointing on the object, and "that" is used for when the object is far or no pointing it. But I don't understand the difference between these two ("this" and "that") and the pronoun "it".





N.B. The same question I can ask about the pronoun "they" and the demonstratives "these" and "those", but in this case "they" is used both for human beings and all the rest, unlike the pronoun "it" which is used for everything except about human being.


enter image description here



Answer



The difference between the two based on the "Cambridge dictionary" article, is as follow (quote):


"We use "it", "this" and "that" to introduce further information about a topic already mentioned. However, the words have different uses.


We use "it" to continue to refer to the topic we are already writing or speaking about:



The heart is the central organ in our bodies. It is used to pump oxygen around the body through the bloodstream. (It refers back to The heart)




Warning: We don’t use "it" when we first give information about a topic, for example immediately after a chapter or section title in a text:


(b) Green application form

*This* must be signed by all applicants and returned by 30 November 2009.

Not: *It* must be signed …

We can use "this" to refer back to whole clauses and sentences and to previous parts of a text. "This" highlights the information referred to much more strongly than it. Writers often use "this" when a point or idea is to become an important part of the discussion that follows:



More and more people are discovering that Tai Chi is one of the most valuable forms of exercise. This has led to a big demand for classes. (This refers back to a whole sentence.)



Heavy rains and stormy conditions throughout the summer have led to severe shortages in strawberries and other soft fruits. This has led to price rises in many supermarkets and shops.



We use "that" in a similar way to this. However, when we use "that", we distance ourselves more from the topic or from aspects of the topic:



For many traditional football supporters, it is a problem that so many young girls and women attend football matches these days. That is a sexist attitude of course.



"That" is also used to refer to ideas associated with another person:



The chairman apologised for the poor performance of the company and promised a better future for investors. That was a promise many people felt he could not possibly keep."




(All of the above is from the Cambridge dictionary. I've just added some graphics such bold letters etc. in order to make it easy for reading and understanding.)


The above Cambridge article deals with the using of "it", "this" and "that", while writing or talking generally. But the original question is also about a case of pointing on an animal or a fruit for example and talking about it. So in that case should we say "*It is a nice animal" or "This is a nice animal"?


It seems that it depends on context. If we are around with the ability to point on the object, meaning that we see it, then we can use "this" or "that" depends on the distance. But if we don't see it at all, we use "it". enter image description here


data structure - In a 2D tile-based game, how should NPCs and tiles reference each other?


I'm making a tile engine for top-down 2D games. Basically the world is composed of a grid of tiles.


Now I want to put for instance NPCs that can move on the map.



What do you think is best:



  1. each tile has a pointer to the NPC that is on its tile, or a NULL pointer

  2. having a list of NPCs, and they have the coordinates of the tile they are on.

  3. something else?


I think



  1. is faster for collision detection but it would use much more memory space and it is slower to find all NPCs in a map.

  2. is the opposite.




Answer



Why not both? There are times when you'll want to look to see if there's any NPC on a specific tile (such as for collision detection, as you mentioned), and other times when you'll want to iterate over all the NPCs in the world (such as for running their AI methods every frame).


A pointer per tile is not that much memory unless you're working on a memory-constrained platform or you have a really huge map.


unity - How to create custom 3D "areas" at runtime


I've been puzzled for a few days trying to solve this problem, so far with no results.


On a map, currently a Terrain, I'd need to have some "areas" which can be controlled by a specific players. The shape of those areas can arbitrarily change during the course of the game, such as you add a marker in any point, and the area evolves (like a spline, say) to pass through that point too.


The problem isn't drawing the boundary itself, of course, but having the GameObjects detecting the area they are in.


Currently I have absolutely zero idea on how to make this exactly.




I've thought about a nice approximation, which is splitting the terrain in fixed chunks, and having the player control them "chunk by chunk": every chunk can have its own collider, and that should be easy if not trivial. So the question is how to do it "properly", since I already have this workaround.




Answer



I solved this problem using an hybrid approach, inspired by:



  • my original workaround

  • @Felsir's post

  • @dnkdrone.vs.drones's post



I have Chunks, which may have an owner or be contested.




  • Inside a contested Chunk, different players have their areas of influence.

  • Instead of using a definite polygon/line border, inside the Chunk itself every player may place Flags.

  • The Chunk itself is dividend into equally distanced ChunkPoints.

  • A ChunkPoint's owner is the nearest Flag's owner.

  • Chunk's % ownership is how many ChunkPoints you own.


first screenshot screenshot with sub-areas



Using a polygon approach turned out to be too complex because I had to detect the order of the points, and they could with time take very complex shapes, which wasn't obvious how to handle.


I considered using voronoi's before realising that a ChunkPoint map was much easier and equally good for what I needed to do (but trying to use them was the source of inspiration that got me there).



In the original workaround idea, Chunks weren't "contested", they were just fully-owned by a single player, and that's why I didn't like them.


Thursday, January 23, 2020

architecture - Handling collisions with ground


How do you usually solve collisions between entities and the ground? Sending collision events hardly seems appropriate since almost everything touches the ground at almost all points in time. Calling collision handling functions doesn't sound any better.


How is this normally achieved? Is handling of slopes significantly harder?



Answer



When you detect a collision with the ground and the speed Y is low, you disable the gravity for that object, set the Y speed to 0 and skip the collision reactions against that floor (store a temporal reference to it) until its Y axis acceleration gets disturbed somehow (because of an external force such as a collision reaction or the character jumping or the floor getting out of range).


You can have many floors then you know that when you are over one floor you don't have to check collision against others, you only check for collision with the floor you know you were last frame, and if you don't collide with it then you wait until a floor object reports its collision and you can start the process again.


EDIT: I forgot to mention that if you're dealing with more realistic physics such as rigid bodies, checking the Y speed may be not enough for non-spherical objects (non-circular in 2d) as an angular velocity may affect your vertical force depending on the shape and momentum of the object.



Note that by identifying the ground objects you can exploit their mutual exclusivity properties in many ways, such as for collision with other objects (an object over a floor doesn't collide with objects that rest over another floor) similar to the way a quadtree works. You may also find place for some prediction there, depending on the rules of your game (more realistic physics will always be harder) you may be able to predict the floor where your object will (most likely) be next, then set that floor as a priority for ground collision checking.


Ah, and for if handling slopes is harder, it depends on the variety of angles for all slopes (in some games the slopes are always 45 degrees or so) and on the way you make your objects slide over a ground, ie you may want that if the Y velocity is high, you slide when falling on a slope, but if your Y velocity is low enough you could stop it. You may also want to add an effect to have different floor materials, so you would slide less over grass than over polished metal.


sentence construction - Do you use the phrase "that which" for the apposition?



The insect propagates best near "disturbed land," that which is being cultivated by humans.



I saw this type of sentence. Do you use this kind of syntax. Would it be possible that it is colloquial?


Some explain that "that" following "disturbed land," is the apposition and also the antecedent of the "which". I often see "that which" phrases but these did not have this apposition like structure.




Difference between cycle and loop


What word of two mentioned above should I use when I mean a map route which begins and ends at the same point?



Answer




Looking at your question, I feel you want to mean that there's a map where you begin at one place and also end at the same.


Cycle does not fit and loop refers more to a shape than what you probably want. Okay...


One of the common words used for this is ...



circuit - A roughly circular line, route, or movement that starts and finishes at the same place



Example of Circuit route


You may also use track but I don't think it starts and ends at the same point whereas circuit does probably because the electronic circuit happens only when it completes its path.


apostrophe - How do I spell the possessive form of children?


In the sentence below, are the usages of apostrophes correct?



In research about parent stereotypes, the correlation between parents’ beliefs about their early elementary age children’s’ mathematics abilities and the children’s actual abilities increased as children aged.




Answer




No. The rule is simple:



  • For regular plurals ending in s, the possessive suffix is '.

  • In all other cases, the suffix is 's.


Children is an irregular plural, not a regular one. Therefore, the suffix is 's, and the possessive form is children's. Your form *children's' is incorrect.


However, the other possessive forms are fine. Parents is a regular plural, so the possessive suffix is simply '. That means parents' is correct. And you correctly write children's later in the same sentence. (Was your earlier mistake a typo?)




In this answer, the * symbol means that the spelling is considered incorrect.


textures - How to compute tangent and bitangent vectors


I have a texture loaded in three.js, then passed to the shaders. In the vertex shader I compute the normal, and I save into a variable the uv vector.






How do I compute the T and B vectors?



Answer



First of all, for every 3D vertex there is infinite tangent and bi-tangent vectors. The below image explains why there is an infinite number of tangent spaces for each vertex, the tangent and bitangent can have any direction in the shown plane.


Infinite number of tanget spaces for each vertex


So inorder to properly calculate the most useful1 tangent space, we want our tangent space to be aligned such that the x axis (the tangent) corresponds to the u direction in the bump map and the y axis (bitangent) corresponds to the v direction in the bump map, we should already have normal of the vertex which already corresponds to the Z direction in tangent space.


(1) most useful because in the end we want normal vectors to be sampled from the texture


That best be explained with pictures, we want our tangent space to be aligned like (u, v) shown below.


enter image description here


Source of the image though not strictly related to computer graphics



In computer graphics developers usually use (u,v) also known as texture coordinates. We will assume T is the tangent and B is the bitangent, and P0 is our target vertex, that is part of the triangle (P0,P1,P2).


First remember what we wanted to do, is to calculate tangent and bitanget that:



  1. T aligned with u and B aligned with v.

  2. T and B lays in the plane with the vertex normal (the plane shown in the above image).


The point is we already assumed that T and B lays in the same plane and corresponds to U and V now if we can know their values we can cross product and the third vector to construct a transformation matrix from world to tangent space.


enter image description here


Given that we know that any 2D vector can be written as a linear combination of two independent vectors2 and since we already have the triangle points (edges), shown in the above image. We can write:




E1 = (u1-u0)T + (v1-v0)B


E2 = (u2-u0)T + (v2-v0)B



(2) actually that's is how basis matrix is derived


The above equation can be written in a matrix form,


| E1x E1y E1z |   | deltaU1 deltaV1 | * | Tx Ty Tz |
| E2x E2y E2z | = | deltaU2 deltaV2 | | Bx By Bz |

By solving the matrixs equation we can determine T and B values we can construct a transformation matrix.


The full source code in C++



#include "Vector4D.h"


struct Triangle
{
unsigned short index[3];
};


void CalculateTangentArray(long vertexCount, const Point3D *vertex, const Vector3D *normal,

const Point2D *texcoord, long triangleCount, const Triangle *triangle, Vector4D *tangent)
{
Vector3D *tan1 = new Vector3D[vertexCount * 2];
Vector3D *tan2 = tan1 + vertexCount;
ZeroMemory(tan1, vertexCount * sizeof(Vector3D) * 2);

for (long a = 0; a < triangleCount; a++)
{
long i1 = triangle->index[0];
long i2 = triangle->index[1];

long i3 = triangle->index[2];

const Point3D& v1 = vertex[i1];
const Point3D& v2 = vertex[i2];
const Point3D& v3 = vertex[i3];

const Point2D& w1 = texcoord[i1];
const Point2D& w2 = texcoord[i2];
const Point2D& w3 = texcoord[i3];


float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;

float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;

float t2 = w3.y - w1.y;

float r = 1.0F / (s1 * t2 - s2 * t1);
Vector3D sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r);
Vector3D tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r);

tan1[i1] += sdir;
tan1[i2] += sdir;

tan1[i3] += sdir;

tan2[i1] += tdir;
tan2[i2] += tdir;
tan2[i3] += tdir;

triangle++;
}

for (long a = 0; a < vertexCount; a++)

{
const Vector3D& n = normal[a];
const Vector3D& t = tan1[a];

// Gram-Schmidt orthogonalize
tangent[a] = (t - n * Dot(n, t)).Normalize();

// Calculate handedness
tangent[a].w = (Dot(Cross(n, t), tan2[a]) < 0.0F) ? -1.0F : 1.0F;
}


delete[] tan1;
}

Full source code and derivation can be found here.


javascript - Click on an isometric plane and obtain normal coordinates


I have photos distributed as cells. When I click, I get the corresponding row and column. console.log("Col:" + X + "Row:" + Y);


When applying an isometric view conversion like this:


ctx.translate(0, 300); ctx.scale(1, 0.5); ctx.rotate(-45 * Math.PI /180);


I do not know what mathematical formula applies to get the coordinates correctly.


Example of isometric map




Based on feedback so far, I've been able to get this far. The x coordinate seems to work fine, but the y coordinate not.


Isometrico();


function Isometrico(){
ctx.translate(0, 300);
ctx.scale(1, 0.5);
var radianes= -45 * Math.PI /180;
ctx.rotate(radianes);
}

/*
document.addEventListener("mousedown", function(e) {

CorIsometrico( e.offsetX, e.offsetY);
});
*/

/*
function CorIsometrico(xI,yI){
//RESPUESTA yI=yI-300;
yI = yI * 2;
xI = xI * Math.cos(45) - yI * Math.sin(45);
I = yI * Math.sin(45) + yI * Math.cos(45);

console.log("Coor Isometricas:" + xI + "/"+ + yI);
}
*/



Edit:


Each cell is 50x50. Having 10 columns and 50 rows, the information of each cell would look like this:


1: 50/50 2: 100/50 3: 150/50 ... 49: 450/250 50: 500/250


Maximum Y value = 250.


xI=xI*Math.cos(45 / 180 * Math.PI)-yI*Math.sin(45 / 180 * Math.PI); yI=yI*Math.sin(45 / 180 * Math.PI)+yI*Math.cos(45 / 180 * Math.PI); yI=yI*2; yI=yI-300;



Click in X:1 / Y:1 = -138.5929291125633/ 531.5575746753798 Click in X:1 / Y:5= 198.69700551341987/ 90.3229432149742


Y exceeds the maximum value.




Edit2:


var xI2=xIMath.cos(45 / 180 * Math.PI)-yIMath.sin(45 / 180 * Math.PI); var yI2=xIMath.sin(45 / 180 * Math.PI)+yIMath.cos(45 / 180 * Math.PI); yI2=yI*2; yI2=yI-300; xI2=xI2+150;


/// console.log("Coor Isometricas:" + xI2 + "/"+ + yI2 );


x coor : 100 to 400 px if x+150; y coor: 0 to -155.


Been thinking that the problem is not necessary on isometry. What I'm looking for can be simplified to get the coordinates of a 2d plane by having it rotated X degrees




tense - after she had her baby; after she had had her baby





  1. Sheila continued to work after she had her baby. (Longman Online)

  2. Silvina continued to work after she had had her baby. (Longman Contemporary)



I would guess that 1 implies Sheila continued her work, pregnant. 2 Silvina continued her work after bearing her child. Are my guesses all right?



Answer




Are my guesses all right?



Not exactly.




Sheila continued to work after she had her baby.



This is the simple past, and it means that she continued work after bearing her child. In English, we use have a baby idiomatically to refer to the act of birthing. Since it's in the past, it means the birthing is complete, and after tells us she did not continue working until after that. The two events are grossly contemporary, both being at some point in the past. Sheila returned to work relatively* quickly; there was no extended period of absence, though we don't know how precisely long it took.



Silvina continued to work after she had had her baby. (Longman Contemporary)



This also means that she continued to work after bearing her child. However, the use of past perfect places the two events at greater remove by indicating they occurred at different times; the past perfect event occurs distinctly before the simple past event. With the simple past, it's possible for the two to happen consecutively, but not so with the past perfect. It's a subtle difference, but we can infer that the time between child birth and continuance of work is likely considerably greater than in the first example. Here, Silvina did not immediately return to work after having her baby; some non-trivial amount of time passed, though we don't know how much.


* - Relatively means different things to different people, and when said about different people. I'm being intentionally vague. We often play a bit loose with the language and depend on the context for nuances. A week's leave to recover from childbirth might be unusually long for one woman (maybe she really loves her work); conversely, a month's might be not nearly long enough for another (perhaps her job requires strenuous physical labor).


Wednesday, January 22, 2020

A comparison between the structures "would rather" and "would prefer"


I know that "i'd rather", like "I'd prefer" is used for specific situation and not general ones. On the other hand I know that the second sentence below doesn't work here. But the question ins that why the second sentence doesn't work here?



1 - I’d prefer coffee to tea tonight.


2 - I’d rather coffee to tea tonight.



My next question is that if "I'd rather" is in common use in AE.




Answer



prefer indicates a choice of things (nouns), while rather indicates a choice of actions (verbs).
Prefer is a tr. verb and rather is an adverb.


So using your examples,



1 - I’d prefer coffee to tea tonight.



this is OK because it is used as a tr. verb.



2 - I'd rather have coffee to tea tonight.




Since rather is an adverb, a verb (both to be modified by the adverb, and just to have one in the sentence), is needed. In this case, have.


continuous - could the second conditional be like this?


From a film subtitle:



"What would've happenned if you were a few minutes later, Hani?"



I think that 'What would have happened if you had been a few minutes later,Hani?'is right? I think this is third conditional sentence. Could you tell me the grammar I don't know? Or is this wrong sentence?



Answer



The sentence you show could be correct in another context, but not in this one, which is reported elsewhere (with a slight and immaterial difference):




HANI: He was in the room because I put him there. I'm just sorry I wasn't there a few minutes sooner.
ROGER: Alright, what would have happened if you were a few minutes later, huh?



Clearly 'Roger' is posing a counterfactual contingency, 'Hani' arriving later than in fact he did; he implies that Hani arrived too late to prevent one sort of misfortune, but early enough to prevent another. You are therefore correct in believing that this should be expressed as if you had been a few minutes later.


You should realize, however, that in improvised speech (which this script emulates) neither speakers nor hearers are particularly attentive to these fine points of expression. Complex counterfactuals like this are relatively infrequent in ordinary speech, and most people don't use or hear them often enough to 'appropriate' them into their unconscious syntactic portfolios. Consequently, you are likely to hear exactly this sort of error very frequently. What Roger means is perfectly clear, and that's all that matters in casual speech.


The lessons to draw from this are



  1. You shouldn't expect improvised speech to be strictly grammatical.

  2. You shouldn't regard such errors as anything but casual and trivial.

  3. You shouldn't use informal speech as a model for your own English. Points 1. and 2. don't give you license to make the same errors yourself. Standards are more stringent in written academic contexts.



Tuesday, January 21, 2020

possessives - "I know Bryan’s height" or "I know Bryan height"?


I know that the first is correct. Is the second correct too? Why?


And two more examples to make it clearer:




I know the tower height



vs



I know the tower's height



vs



I know height of the tower





Answer



English is flexble and allows many nouns to function as modifiers, but it has a subtle effect on meaning.



I know the tower height.



Here, I understand that height is a noun, and tower is an adjective answering the question height of what? or what kind of height?.


But this makes it seem like tower height as in "the height of a tower" is an important idea or concept on its own and that the listener/reader ought to be familiar with that or the reason for that - e.g. in this case, heights of towers seem to be something that you work with so much that you are shortening the words used to express it.


Usually you want to avoid this unless you are getting into the technical jargon of a profession or "shop talk".


Now, given the above, if you were to do this with a proper noun, you would be de-personalizing, as though the proper noun is just a thing, or a non-human object. And of course, since it's a modifier, you still need your article in front of it.




I know the Bryan height.



Here, it seems you are saying that Bryan is not a real person - I would guess it's some technical jargon, some aspect of a craft or profession - like "Pythagorean theorem" or similar.


Now:



I know the tower's height


I know the height of the tower



mean the same. X's Y can mean "Y physically belongs to X" or "Y that which is an attribute/quality belonging to X".



How can I create an efficient bloom shader with GLSL?


I have searched the net for resources related to rendering a bloom effect using GLSL, but haven't found anything. Although the tutorial at Philip Rideout's website is a good one, it performs very poorly on my Nvidia GPU.


Can anyone guide me as to how should I approach this problem and build a fairly efficient implementation of a bloom effect?




Monday, January 20, 2020

word usage - the exact time of "evening" and "night"




I wonder what the exact times of the following words are: morning, noon, afternoon, evening, night, mid-night.


What's the difference between at night and in the night?




How to design a turn-based game which is easy for humans but difficult for AI?


Until recently, Go used to be of the last bastions of turn-based no information-hiding games where world-class human players could not be defeated by computers. But now this bastion has fallen, as the program AlphaGo managed to beat one of the world top players.


However, Go was never designed as a game which is hard for AI. It was developed thousands of years ago. Being hard for computers was an unintentional side-effect of the game design, not a stated design goal.


What game mechanics make a turn-based strategy game without information hiding hard for AI, yet still playable for humans?




In case someone wonders "Why is this question also relevant for video game developers"?




  1. because it shows us how to design competitive multiplayer games where players can not cheat by using an AI assistant.

  2. For single player games it shows us what to avoid when we plan to add an AI opponent later.




word choice - "have been to" versus "went to"


I have read this sentence in an English course textbook:



I have just been to the bank.



What we know about the person who says that sentence is:




  • He went to the bank in the morning.

  • He was there, doing some paperwork.

  • In the present time, he is at home.


I don't really know if been to is equivalent to:



  1. I have just been in the bank.

  2. I have just gone to the bank.

  3. I just went to the bank.





pedagogy - Ways to organize an ESL course?


I'm working on a game to learn English, and grappling with the best way to organize the course. It would be great to hear from people what they've liked when using other apps.


I guess there are a few approaches:




  1. by difficulty level split grammar up by level. eg start with "simple past" and move to causative or passive until later. same for all other grammar types




  2. by grammar grouping eg verbs / noun forms / modals / pronouns ... and the various sub-types of each. modals of advice/requests/ability would be a subtopic of "modals" etc.





  3. by random grouping group topics together that fit well together, to make lessons with more flow and variety. eg put conditionals and comparatives together, so you can teach something like "If you pick the largest one..."




I built a site for learning Japanese (JGram.org) and the grammar there is much smaller chunks. For example this list of "level 2" items: http://jgram.org/pages/viewList.php?lv=2


has patterns like "despite / just / it seems / because / without / it's decided " ... These are more like useful one-off sentence patterns, not quite idioms or phrases, but I'm wondering if there's any way to organize those types of items at a higher level?


If there's a better forum for this type of question, I'd love to know, otherwise any comments appreciated!




Sunday, January 19, 2020

algorithm - Generate islands/continents with simplex noise


Managed to get something like this using a simplexnoise port i made from the original javacode to php:


enter image description here


Used some tips from other post:


Understanding Perlin Noise


basically, lowered the frequency to get more flat terrain.


Now, how could i foce the map to be a huge Pangea? If i manualy set for example, if (x < 5) set height = 0 (water), when i normalize all the map to 0...1 the value 0 get higher (as my simplexnoise function returns -1 1). If i force it to -9999, does not work either.



Has to me something elegant to sneak into the height generation code to make the borderline squares, water.


With MDP algorithm i could seed the sides of the map to -500 for example and then pretty coast would be made, but with simplex/perlin does not seem the case as i can not enter pre-seeded cells with artificial heights.


Any tips?




numbers - First, Second, Third, Fourth or 1st, 2nd, 3rd, 4th? One, Two, Three or 1, 2, 3?


When we use words like first, second, third, fourth or 1st, 2nd, 3rd, 4th, in sentences, what will be the best way to write these? Also, what about numbers? Do we put them as numbers or numerals?


Here are some sample sentences,



  • He got first/1st class in that examination.

  • He gave me two/2 books.

  • He will be the first/1st to get there.

  • My son is finishing his seventh/7th semester.

  • The turkey weighed five/5 Kg.



Yes, I understand that we can have many examples like the above.


Do you think that you can give some general rules for these?



Answer



I think it's better to spell out numbers while writing essays or letters or related pieces. (In Mathematics or any Science subject or Commerce subject can one freely use the numbers.)
Also, for giving measurements, The turkey weighed five kilograms seems better than The turkey weighed five Kg. When you are already writing out the number in words, why write the unit in the short form? Spoils the look.


word choice - What is the difference between 'east Indian' and 'eastern Indian'?


I read the following line in NYT:



A surging crowd near a Hindu temple killed at least ten people and injured 25 others in the eastern Indian state of Jharkhand on Monday, police said.



Now, my questions regarding this line are:



  1. Can we write 'the east Indian state' instead of 'the eastern Indian state'? What is the difference between them?

  2. Which one is more preferable? In India, I have come across many sentences with 'east Indian state' clause.





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