Saturday, January 30, 2016

networking - How do I sync multiplayer game state more efficiently than full-state updates?


I've done a little game network coding before, but primarily with TCP for games without real-time needs. I am working on a 2D Java game with networked multiplayer. For learning, I want to do this myself, without an existing network API.



How do I efficiently represent the game state sent to clients from a server? There is the most obvious but probably least efficient way, which would be to create some sort of game state context object with each player's location, animation state, etc., and send that out to each player every update. That doesn't seem terribly difficult to implement, but would probably be too large to achieve anything close to real-time interaction (of course my experience with this is limited so I may be incorrect).


Is there a solid way any of you have used before to only transmit changes in state, and is there even a large enough disparity in performance that it is worth the extra work?




prepositions - What is the difference between 'located in' and 'located on'?


I am solving the TOEIC workbook, by the way, I faced conflict that doesn't match meaning I knew.


The problem is




The newest branch of the library is located in/on Pine Street.



I think either 'in' or 'on' have the same meaning. But the commentary said that 'be located in' is mainly writing in front of building name and city name.


I don't know what is correct?



Answer



Prepositions are so versatile in their usage that it's difficult to give exact rules on their usage. However, here is rough guideline from English Club: Prepositions of Place: at, in, on



In general, we use:



  • at for a POINT


  • in for an ENCLOSED SPACE

  • on for a SURFACE



at Point                in ENCLOSED SPACE   on SURFACE   
at the corner in the garden on the wall
at the bus stop in London on the ceiling
at the door in France on the door
at the top of the page in a box on the cover
at the end of the road in my pocket on the floor

at the entrance in my wallet on the carpet
at the crossroads in a building on the menu
at the front desk in a car on a page

Using the OP, we have



The newest branch of the library is located on Pine Street.



You use on when you want to talk about a building and its relation to a street. Roughly, you can consider the street as a "surface" so that it follows the guideline above.


The street is not really a point, so we don't use at. However, a specific address, like 123 Pine Street, is considered a point. In such a case, you could use at:




The newest branch of the library is located at 123 Pine Street.



The street is not really an enclosed space, so we don't use in. However, a specific city, like Los Angeles, is consider an enclosed space. In such a case, you could use in:



The newest branch of the library is located in Los Angeles.



I think the commentary you mentioned is referring to this specific example above. Referring to "writing in front of building", it's possible to use in. For example, there could be a sign in front of the building that reads



Our collection of contemporary works is located in this building.




Here, you can use in because the building is considered an enclosed space.


Is there an alternative way to express "has them " other than "makes them "?


For example, in the following sentence, can I replace have them with makes them, or is there another verb that more correctly I could use instead of has?



Since the manufacturers are so deeply involved, in some cases Wal-Mart even has them handle their own distribution, saving the retailer big bucks and increasing profit margins on cheaper goods.



Another example could be the following one.




The doctor sends my father and Uncle Johnnie out for all the ice they can get. Then he has them dump the ice in the bathtub, add cold water almost to the top, whereupon my aunt is wrestled into the tub and submerged.




Answer



There are several constructions of the form



  • have NP VP (to not allowed)


One of them is a causative construction; as noted, there are other causatives as well. A causative always entails that an event happened or a state changed; but there are different ways to cause this, and different ways to talk about it.





  • make NP VP (to not allowed)
    I made him examine me means I forced him to do it.




  • get NP to VP (to required)
    I got him to examine me means I had to persuade him to do it.




  • caused NP to VP (to required)

    I caused him to examine me means only that he did it and I was responsible. It's very formal.




The causative have NP VP construction is quite common with a past participle clause



  • I had my tires replaced yesterday, while my car was in the shop.
    (basically a passive with indefinite subject, from I had them replace my tires)


There's another very different have NP VP construction - the subject is not the agent but the patient.




  • I had my tires slashed last night, while my car was parked outside.


This one is always passive and often (though not always) deals with a bad outcome



  • I had my dearest dreams crushed by their betrayal.

  • I had my wildest dreams fulfilled by their assistance.


2d - How to calculate shot angle and velocity to hit a moving target?


I am developing a 2D Android game and I am making an aiming algorithm for AI projectiles to hit enemies either following a path, or free moving. At the moment it just calculates where the target will be after a distance and fires a projectile to meet it at that distance. Of course this means varying the projectile speed to meet the target.


Does anyone have any tips for a simple-ish algorithm (optimal-ish) to calculate when the projectile needs to fire and where it needs to aim if it can only travel at a constant velocity? Say the projectile goes twice the speed of the target?


The only way I can think of involves searching and seems quite large.




Friday, January 29, 2016

grammaticality - Why are "software", "advice", and "information" uncountable?


Sometimes in English I encounter words which are uncountable, while they may be countable in my native language causing some mistakes in my sentences, and I wonder why they are uncountable.


For example "software"; we look at any application, *a software (as it is used by software companies)



*I developed a software


*It is a software to edit pictures



Or "advice", it could be countable too, pointing to any useful sentence or point one could say:




*That was a good advice


*As a friendly advice


*There were many good advices in this story to learn



Or "information". Now, I can't remember, but you may count more such words, if you have a problem with them.


I know the following is grammatical in English:



  1. a piece of software

  2. a piece of advice


  3. a piece of information


but in these cases piece just looks redundant. One day, could "piece" be omitted, and these uncountable nouns become countable? Why are "advice" and "information" uncountable when in many Romance languages they are not?



I'd like some information about train times please.


Although 'information' is countable in many languages, it is uncountable in English. (British Council)




  • Do you know words which were once uncountable but later become countable?






  • I would like to understand why some nouns are uncountable in English while in other languages they are not.




gerunds - Problem Choice Grammar questions


I have come across in exercise a sentence presented like this:



I decide that NOT GO/NOT GOING would be the better decision.



Between NOT GO/NOT GOING I 've selected Not go but the right answer is NOT GOING.



Why is 'not going' the correct answer?




word choice - How can I remember the difference between "lay" and "laid"?


I often confuse lay and laid. For instance, in selecting the appropriate word in these contexts:



She lay/laid a hand on his arm.
He lay/laid across the bench lazily.
We lay/laid down our heavy load.



Is there a common mnemonic for remembering which to use, and when?




Game programming books that don't teach programming?



I am an normal programmer with about 3 years of experience, who is interested in getting into game development. The problem that I face is that when I look at these "beginner" books, most of them teach basic programming skills, and I don't have the patience to sit through it or find them worthwhile. But, when I look at more advanced books, they're over my head, and once again, fruitless to me. What I'm looking for, are books that explain the nitty-gritty internals of games, but at a more reasonable level.


For example, I'm very familiar with all kinds of data structure (hashes, trees, linked lists), and with many common algorithms (sorting, searching), but I wouldn't know how to, say, implement collision detection effectively. I also have experience using foreign libraries, so I know how to use documentation to learn an API, so I don't need a "Learn to use X" book either.


Personally, I don't care what platforms/languages/libraries are used in the books, since I'm comfortable in many languages, but the game I'm looking at making would use Javascript and the HTML5 canvas.


Any suggestions? Any that are free?


P.S. I should note that my level of mathematics and physics is relatively low, and a book that gently integrated those things would be a plus.


EDIT: I should mention that I'm interested in 2D programming, and at this point I don't really care for 3D yet.




meaning - Is "supposed to play" semantically different from "supposed to be playing"?


Is there any meaning difference between these two sentences?



I was supposed to play.




I was supposed to be playing.





Answer



Yes, there are differences. How they differ really depends on the context, but I will give some examples to clarify.


(Unlike some languages, English isn't as strict about whether a tense grammatically indicates a specific aspect, nor whether a verb lexically does so. This complicates things by giving us more possibilities.)


"I was supposed to play." indicates either that someone expected the speaker to play on one occasion, or that someone expected the speaker to play for some amount of time. Here are two examples with more context:


"I was supposed to play baseball yesterday but it rained." We're thinking of "play" as a single activity within that day. (This is the perfective aspect, because we mainly care about the action being completed.)


"I was supposed to play football that summer, so I didn't join the baseball team." Here, we're instead thinking about many instances of playing as a reoccurring activity. If I say "I play baseball.", I mean it generally. I don't mean that I'm playing it right now.


Now, the second: "I was supposed to be playing." The simplest way (but not the only way) to think of this is that someone expected me to be playing now. Here's some context:


"My coach is angry because I was supposed to be playing baseball right now." (We planned or agreed that I would play, and I'm not doing it now.)


Continuous tenses are funny in English, because we can use them for multiple meanings. A second use of "playing" can emphasize activity during a time period (similar to "I play baseball every Friday." but emphasizing the activity more, as in "He never stops! Every Friday, he's outside playing baseball!"). This can be for several reasons, but here's one example of that, used to indicate repetition: "Why are you spending your summer at home!? You're supposed to be playing baseball!!"


We also often use a continuous tense to emphasize that something is temporary, even if it happens over a long period of time. "I play baseball a lot, but I hurt my arm and I'm playing soccer/football until I feel better." To use this with "supposed to": "The baseball team didn't have enough players, so I'm supposed to be playing baseball this week, but after that I'll play basketball again."



What makes this even more complex is that a continuous tense "to be playing" can sometimes be used to describe the future. For example:


"I'm playing baseball with them next week." This is a more natural way to say "I will play baseball with them next week.", with a feeling that it's already planned and that there is some "momentum" leading toward the playing.


I can use the infinitive form of this, "to be playing", with "supposed to" like this: "I'm supposed to be playing baseball with them next week, but I'll call them to be sure." Often, this form is used when I've planned or arranged an activity with other people.


So, to summarize:


"I'm supposed to play..." can mean that I'm supposed to play on one occasion, or several times across a longer time.


"I'm supposed to be playing..." can mean that I'm supposed to be actively playing at this second, can mean that I'm playing over a longer time (but emphasizing activity, repetition, or that it's temporary), or that it will happen in the future (often with a plan involving other people).


conditional constructions - When I put 'is' instead of 'be' in: "If she be found guilty"



If she be found guilty… (YBM #8)




I got a curiosity what difference there is when I put ‘is’ instead of ‘be.’ The dictionary says ‘is’ is used in spoken language. Is that all? Is there no semantic difference at all?



Answer



This is a remnant of the old subjunctive, which is no longer used in Standard English conditionals outside of historicizing contexts. You may freely substitute either a simple present or should be—except, of course, in quotations:



If this be treason, make the most of it! —Patrick Henry


Fee, fi, fo, fum
I smell the blood of an Englishman
Be he alive or be he dead
I’ll grind his bones to make my bread —Old tale



If music be the food of love, play on. —Twelfth Night



2d - How do I detect how much of an object has been "cleaned" by the player?


I want to let the player wipe some dust off of a book, then start a short animation.


Here's what it looks like:


What it looks like, with some dust wiped off


I'm using a clipping region on the "dusty" book bitmap image to progressively hide the dust as the player mouses over it.


However, I'm stuck with how to detect when the dust is all gone. What's a good way of tracking how much is left?




Thursday, January 28, 2016

meaning - Third Conditionals: "If I knew..." instead of "had known..." in casual register


I know that in the following sentences "If I had known" has to be used in the place of "If I knew" to form the grammatically right sentences. What I really want be sure of is that as a native if all the 3 examples given below sound natural to you though or do you find it odd using it that way and so on? cause I've come across this to be used that way pretty often and it makes me wonder.


Please mention sequences of verb tenses in your responds too..(e.g, In the first example Subject wishes to be informed of the object's coming as s/he was on the way. looks like same time action)





  1. If I knew you were coming, I would've arrived from work earlier




  2. If I knew you would/were gonna come, I would've arrived from work earlier





  3. If I knew you had come, I would've arrived from work earlier







How to update a game off a database


I am currently writing a sports strategy management game (cricket) in PHP, with a MYSQL database, and I have come across one stumbling block - how do I update games where neither player is online?


Cricket is a game played between two players, and when they (or one of them) is online then everything is fine; but what if neither player is online? This occurs when championship games are played, and these games need to happen at certain times for game reasons.


At the moment I have a private web page that updates every 5 seconds, and each time it loads all games are updated; but then I have the problem that when my private web page stops (for example my computer crashes or my web browser plays up) the game stops updating!



Answer



As some of the comments mentioned, the issue is that you are trying to get the behaviour of a real-time simulation via an event-driven application.


Your options are basically these:



  1. Create fake events to ensure the web page is accessed when you need to perform these updates. This could be a cron job that polls a certain page. (However, if you have a system capable of running periodic cron jobs to access a web page, you should probably just have that system perform the update itself. See below.)

  2. Make the system perform 'just-in-time' updates. Games don't actually need to occur when nobody is looking at the page - they just need to have seemed to have occurred whenever someone next looks at the site. So, you have a routine, usually included on every page in your game, which checks for overdue updates and executes them immediately, before returning the rest of the page as usual. So if nobody accessed the site for a week, the next visitor would trigger off one week's worth of updates, and would see those events as expected. This is probably the easiest route and I expect it would work well for you.


  3. Have the database perform timed updates. MySQL offers events that can run stored procedures. This is ok, providing that you can write all your game logic in your database's stored routine syntax. Usually this is impractical.

  4. Use your own long-running process (ie. a daemon as mentioned in comments) to host your game instead of one that only runs for the duration of serving up a page. There are many languages and systems that can do this, almost all of them arguably better for programming games in than PHP, but usually not as quick to get started with. They also tend to require more expensive hosting. But since they run permanently in the background while waiting for incoming HTTP connections, it is usually easy to implement background jobs that perform timed updates of your choosing, whether someone has connected to the site or not.


sentence construction - Go (to / in) your own way


Imagine a son who wants to work as X in the future (an occupation that seems quite odd to others.)


For this reason, the surrounding people and his friends start to mock him or treat him outrageously in an annoying way!


He decides to consult his father and ask him for his opinion about his goal. His father finds nothing wrong with that. He wants to ask his son to pursue his dreams and encourage him to go to the way he likes himself regardless of what others say. I was wondering which option below works grammatically and idiomatically natural in my example:



_________________________. Don't care about what others say.



a. Go your own way.
b. Go to your own way.
c. Go in your own way.



If non of them works in this sense, then I was wondering what should I say?



Answer



In idiomatic English one would say



Go your own way



another English phrase meaning the same is



Plough your own furrow




"Go to in your own way" is not used as far as I know, whilst



Go in your own way



This rarely heard, but has the meaning "use the mode of transport you want to", for example go by bicycle possibly when most people would catch a bus. "Go your own way" could also be used with this meaning, depending on context.


Wednesday, January 27, 2016

parsing - Parts of Speech of: come+ verbing



He came walking


He came waving both hands


He came yelling



And



They left crying




Do you parse walking, waving, yelling and crying as verbs? If not, what would you parse them as?


Edit: crying added



Answer



They are verbs, of course--present participles. Waving, for instance, takes a direct object, his hands. Syntactically they are (take a deep breath before you try to say this)



  • subject-oriented predicate adjectivals


That is: they play the role of adjectives in describing a noun; the noun they describe is the subject; and they occur in the predicate, among the dependents of the verb, rather than being included as attributive adjectives in the subject.


Exactly the same thing can be done with ordinary adjectives and adjectival past/passive participles.




He came home wounded.
He came home elated by the news.
He came home happy.
He came home naked.



None of these describes the quality of the movement: they describe the subject.


There are also object-oriented predicate adjectivals, which likewise may be ordinary adjectives or present or past participles (with or without dependents):



I drink my coffee black.
I drink my coffee steaming.

I drink my coffee loaded with whipped cream.



opengl - glDrawElements Crash


This is the "init" code of the Renderer class:


glGenBuffers(1,&_idVBO);
glGenBuffers(1,&_idEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_idEBO);
glBindBuffer(GL_VERTEX_ARRAY,_idVBO);

GLint lUV = glGetAttribLocation(_SID,"inUV");

GLint lPosition = glGetAttribLocation(_SID,"inPosition");

glEnableVertexAttribArray(lPosition);
glEnableVertexAttribArray(lUV);
glVertexAttribPointer(lUV, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glVertexAttribPointer(lPosition, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat)));

...and this is the "flush" function:


glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_idEBO);
glBindBuffer(GL_VERTEX_ARRAY,_idVBO);

glBufferData(GL_ARRAY_BUFFER,_lVBO*sizeof(GLfloat),_pOriginVBO,GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,_lEBO*sizeof(GLuint),_pOriginEBO,GL_STATIC_DRAW);

glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT,0);

The glDrawElements call crashes with error code c0000005, which is caused by memory acces violation i.e. bad pointers. But I do not understand where the problem is. Any ideas? Thanks in advance...



Answer



One (or more) of your gl calls previous to glDrawElements is not being passed correct information. So when you finally get to glDrawElements it crashes on you because that information is not set properly. Here is what I do to debug that issue:


After each gl call place a ChecKGLError(); Here is that function:


void _CheckGLError(const char* file, int line);


#define CheckGLError() _CheckGLError(__FILE__, __LINE__)

void _CheckGLError(const char* file, int line)
{
GLenum err ( glGetError() );

while ( err != GL_NO_ERROR )
{
std::string error;

switch ( err )
{
case GL_INVALID_OPERATION: error="INVALID_OPERATION"; break;
case GL_INVALID_ENUM: error="INVALID_ENUM"; break;
case GL_INVALID_VALUE: error="INVALID_VALUE"; break;
case GL_OUT_OF_MEMORY: error="OUT_OF_MEMORY"; break;
case GL_INVALID_FRAMEBUFFER_OPERATION: error="INVALID_FRAMEBUFFER_OPERATION"; break;
}
std::cout << "GL_" << error.c_str() <<" - " << file << ":" << line << std::endl;
err = glGetError();

}

return;
}

How does someone go about selling a game or making a royalties deal with Nintendo(or Pokemon Company)?



It seems like Niantic did just that. If someone were to create their own game(Pokemon, hypothetically), how would they, if at all possible, sell that game to Nintendo or at least make a royalties deal? Or any other game, for that matter?




java - How do I limit the rotation speed of a mouse-following object?


I am trying to make a 2D top-down game where player controls a spaceship. The spaceship (a rocket) is just a sprite following the mouse cursor with a fixed speed and is always pointing toward the cursor location. I calculate rotation using atan2(yDistance, xDistance). I've already implemented movement to cursor and rotation toward cursor;


float XDistance = Xplayer - Gdx.input.getX();
float YDistance = Yplayer - (Gdx.graphics.getHeight() - Gdx.input.getY());

rotation = (float) Math.atan2(YDistance, XDistance);


if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) {
if (XDistance >= playerSpeed | YDistance >= playerSpeed | XDistance <= -playerSpeed | YDistance <= -playerSpeed) {
Xplayer -= (float) (playerSpeed * Math.cos(rotation) * deltaTime);
Yplayer -= (float) (playerSpeed * Math.sin(rotation) * deltaTime);
}
MathUtils.clamp(Xplayer, 0, Gdx.graphics.getWidth());
MathUtils.clamp(Yplayer, 0, Gdx.graphics.getHeight());
sprite.setPosition(Xplayer - sprite.getOriginX(), Yplayer - sprite.getOriginY());
sprite.setRotation((float) Math.toDegrees(rotation));


This algorithm makes U-turn (and every rotation in general) instant. I want to achieve a smoother rotation. Instead of instant rotation, I'd like to implement either a curve or simply a bit slower, non instant rotation (while still moving towards cursor current location).


Also, instead of fixed velocity, I am trying to implement acceleration and deceleration, but to no success (for now).


I've already googled lots of various algorithms, but never found the right one.


Update:


public class PlayerEntity {

private float movementSpeedMax;
private float rotationSpeedMax;
private float decay;

private float destinationX;
private float destinationY;

// player
private float playerX;
private float playerY;
private float rotation;

// global
private float _dx;

private float _dy;

private float _vx;
private float _vy;

private float actualRotation = 0;

public PlayerEntity(){
movementSpeedMax = 1000;
rotationSpeedMax = 15;

decay = .95f;
destinationY = 500;
destinationX = 500;
playerX = 0;
playerY = 0;
rotation = 0;
_dx = 0;
_dy = 0;
_vx = 0;
_vy = 0;

actualRotation = 0;
}

public int getX() {
return (int) playerX;
}

public int getY() {
return (int) playerY;
}


public float getAngle() {
return rotation;
}

public void updateRotation() {
// calculate rotation
_dx = playerX - destinationX;
_dy = playerY - destinationY;


// which way to rotate
float rotateTo = getDegrees(getRadians(_dx, _dy));

// keep rotation positive, between 0 and 360 degrees
if (rotateTo > rotation + 180) {
rotateTo -= 360;
}
if (rotateTo < rotation - 180) {
rotateTo += 360;
}


// ease rotation
actualRotation = (rotateTo - rotation)/ rotationSpeedMax;

// update rotation

if (actualRotation < 180);
rotation += actualRotation;

}


/**
* Calculate Position
*/
public void updatePosition() {
// check if mouse is down
if (Gdx.input.isButtonPressed(Input.Keys.LEFT)) {
// update destination
destinationX = Gdx.input.getX();
destinationY = Gdx.graphics.getHeight() - Gdx.input.getY();


// update velocity
_vx += (destinationX - playerX) / movementSpeedMax;
_vy += (destinationY - playerY) / movementSpeedMax;
}

// apply decay (drag)

_vx *= decay;
_vy *= decay;


// if close to target, slow down turn speed
if (getLength(_dx, _dy) < 50) {
actualRotation *= .25f;
}

if (getDistanceCorrect(destinationX, playerX, destinationY, playerY) < 5) {
_vx = 0;
_vy = 0;
}


// update position
playerX += _vx;
playerY += _vy;
}

private float getLength(float delta_x, float delta_y) {
return (float) Math.sqrt((delta_x * delta_x) + (delta_y * delta_y));
}


private float getDistanceCorrect(float x1, float y1, float x2, float y2) {
return (float) Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
}

private float getRadians(float delta_x, float delta_y) {
float r = (float) Math.atan2(delta_y, delta_x);
if (delta_y < 0) {
r += (2 * Math.PI);
}
return r;


}

private float getDegrees(float radians) {
return (float) Math.floor(radians / (Math.PI / 180));
}

}


I've created this class (based on someone's solution on actionscript). However, this implementation has very annoying bug. If the character rotates clockwise, he will instantly rotate counter-clockwise by ~360. I need help in solving this problem.


This instant rotation happens after one full rotation (rotation direction doesn't matter).





uncountable nouns - The furniture is/are



The furniture in our classroom ___ uncomfortable.



Should I use is or are here? I found on the internet things like all of furniture is and house full of furniture is. But nothing about my example. Personally I think that correct is is, but website where I found this says that correct is are. So I'm writing here to find out.




plural forms - There's vs There are


For example:



There's two options here




or



There are two options here



I hear a lot of people say the first line (or something similar), but isn't that incorrect? Isn't it plural and therefore you should use "there are"?



Answer



Here's an edited version of a post I did for ELU on a similar question (which got closed):


The existential construction takes there as a subject. There has no meaning, and often the verb takes its agreement from the complement of the verb BE. So if the Noun Phrase after BE is plural, the verb will usually be in a plural form. If the Noun Phrase is singular it will usually be singular:



  • There is an antelope over there.


  • There are some antelopes over there.


Notice, however, that in the examples above, the subject and the verb BE are not contracted. In normal speech these will nearly always be contracted. We will use there's instead of there is. It is also quite common nowadays to see them contracted in writing, normally in informal texts, although you can find instances in prestigious newspapers like the Times, for example.


Now when the subject there and BE are contracted like this, the verb doesn't need to agree in any way with the following Noun Phrase. Therefore with regard to the Original Poster's example, if they had said:



*There is two options here.



... this sentence would be regarded as ungrammatical by most, if not all speakers. However because they did contract there and BE, it is grammatical:



There's two options here.




This makes this sentence similar to a famous lyric from one of John Lennon's songs:



Imagine there's no countries.



Or usages such as:



There's times when I've wanted to box his ears



Having said this, despite the fact that this is a well documented aspect of the grammar, some prescriptivists are bound to take offense at this. They will insist that it's ungrammatical to use a plural noun after there's. This will be despite the fact that they quite subconsciously actually use plural nouns after there's themselves quite frequently. They will appear about five minutes after I post this answer. They do make life fun though!



There are some other special situations where we might use there is with a plural noun phrase, even though it is not contracted. For example How many people live in your house? Well, there is me, my grandad, my mum and my aunt. If you'd like to read about these exceptions, there's some good posts here!.


Is "go to school" a phrasal verb?


I remember when first I heard "I should go to school" the phrase was odd to me. We don't say "I should go to the / a / my ... school", school has no article, then I think it is the sign that the whole phrase "go to school" is a verb. right?


it is just an example and I think such phrases are much more. Other examples are:




Go home


Get back to work





Tuesday, January 26, 2016

dev groups - Where can I meet other independent game developers?



I live in a large urban area and suspect there are groups of independent game developers that meet to discuss games and just hang out. Are there any clubs or groups or associations or whatever for indie devs?



Answer



Yes! Indie developers tend to be very social. Without knowing which city you live in, it's tough to say what's available, but check out the IGDA's chapter list:



Though these events include students and non-indie industry members, your fellow indies will often be there in force. For example, here in Boston, we have the Boston Postmortem group which meets monthly:



And there's a large enough dev scene in the Cambridge/Boston area such that we even have a monthly meeting specifically for indies:




Generally speaking, once you start networking with other local indies, you'll find out about everything that's going on in your city, whether you want to or not.


Good luck!


Sunday, January 24, 2016

What preposition would you use?



Do you say I´ll arrive in the first week of July? or on the first week of July?




The usage of "in + past tense of a verb"



Then the wolf was very angry indeed, and declared he would eat up the little pig, and that he would get down the chimney after him. When the little pig saw what he was about, he hung on the pot full of water, and made up a blazing fire, and, just as the wolf was coming down, took off the cover, and in fell the wolf; so the little pig put on the cover again in an instant, boiled him up, and ate him for supper, and lived happy ever afterwards.



This is from "The story of The Three Little Pigs" in English fairy tales.


I think "in fell the wolf" means "the wolf fell in the pot" but I don't know the usage of "in + a past tense of a verb" like "in fell". The usage like this is commonly used?




phrase usage - "Do the needful" -- Why is it used instead of asking a question?



Update: (Originally this was a comment, but I thought it was worth sharing here at the top.)


In the original question, I asked if there was a polite, socially-acceptable way to ask an Indian co-worker not to use the phrase "do the needful", as I didn't care for it.


In the years since I asked this question I've asked many people about the phrase. To the Indians I've asked in-person, it's not rude in any way. To Americans I've asked it varies anywhere from "I don't like it, but I don't mind it" to "It's very rude and makes me angry when I see it".


Through a long series of edits the question morphed and I wasn’t able to delete it because it had upvoted answers. The question, as it stands now, has no other answer.


I guess, though, if you're non-Indian and you find it rude, or if you're Indian and you've never realized someone might find it rude, this post may still have merit. Hopefully it does. It certainly has gotten a lot of views. Best wishes, folks.


End Update. See below for what's left of the actual question.




"Do the needful."


It's a phrase that I've only seen used in email, and I find it . . . presumptuous (maybe even rude). Regardless of prefacing with "please", one is commanding rather than asking for assistance.


I've only seen it used by those of Indian origin, so I've simply not mentioned it at all rather than worry about any cross-cultural offense that may come of bringing it up.



But still, I don't understand why it's used. Why not request rather than make two statements, one factual, one imperative?


For example, why would one use:




  1. I'm told you have Jane's email address. Please do the needful.



instead of,





  1. Would you send me Jane's email address?





phrase usage - Let's start where we stopped


Is this phrase idiomatic?




"Let's start where we stopped"



If it isn't then what is the right phrase?



Answer



I can't really imagine many people using OP's example. The most common thing would probably be...



Let's pick up where we left off



That's definition 7 in macmillandictionary




to pick up - to start something again, from the point where you stopped (italics mine)
Example: He seems to think that we can get back together and just pick up where we left off.



...plus this definition from Cambridge Dictionary...



to leave off (sth/doing sth) - to stop, or to stop doing something
Example: This novel begins where the other one leaves off.



Saturday, January 23, 2016

grammar - Article omission or not?



I'm not a native English speaker, so I'm often wrong when it comes to grammar. I usually go with my gut feeling.



I'm documenting some parts of an application and I was reminded that I often omit the the article in my sentences. So we started discussing individual cases but I was objecting to my very best knowledge why the should not be part of them but I'm not sure.


I would still like to write them correctly even though none of us are native speakers.




  1. The donut chart is used ...



    I wrote it without the article because in my understanding the refers to noun chart which in this case is well defined by the word donut so I would say it doesn't need an article. And it's about a donut chart that is the only one on the component I'm documenting.




  2. The chart slice sizes are ...


    I also omitted the article, but in the end I think my sentence was wrong, because article here refers to slice sizes and I should actually wrote it as Chart's slice sizes and of course without the article.




  3. top part with the date period selector


    This is the whole text of some bullet point. I omitted the article because it refers to a specific selector. A date period selector specifically.





Etc... As said, this is all very fuzzy to me.



Answer



Unless you are using "headlinese" for a specific purpose (as in a PowerPoint presentation, for example), then you would include the article; i.e.,



"The donut chart is used" to show the relationships, etc.


"The chart-slice sizes are" indicative of the relative importance, etc.


"The top part with the date-period selector" enables you to, etc.



Another interpretation of this second conditional sentence


Consider:



If I met John, I would call my mom.



I know this sentence is a second conditional example, which relates to a hypothetical situation.


But I don't know whether I can also understand it in such a way if the covert context is:



I may have met him, but I am not quite sure about that. My memory can't last that long. The only thing I am sure about is that whenever I meet him, I will call my mom immediately. Thus, if one day I find out I indeed met John before, I will be sure that I called my mom immediately on that occasion.





Answer



This is exactly why the notion of '1st, 2nd, 3rd conditional' is so useless for anything except getting an initial familiarity with the forms. This sentence, as you conjecture, bears two entirely different meanings in different contexts:




  • It may be a non-past, unreal conditional:



    I don't follow football, but in the unlikely event that I ever met John Elway I would call my mother immediately: she's a huge fan of his.






  • It may be a past, real conditional:



    That summer, Mom didn't mind who I played with as long as she knew where I was; so whenever I met John I would always call my mother.





Your scenario—“I am not sure whether I met him sometime last summer. But if I did meet him at that time, I would call my mom and tell her about him.” requires a different construction in the consequence clause, and would probably employ a construction with do in the condition clause:



I don’t remember if I met John last summer; but if I did meet him, I would have called my mother.




The n-conditional model won’t help you with that: it waves the situation off as a ’mixed conditional’.


prepositions - at IKEA or in IKEA?


I'd like to use the phrase: "Let's buy it at IKEA!" I'm not sure if I should use "at" or "in" in that particular case. Maybe both work? Is there any difference between them?



Answer



English speakers say they are at the store. If they are inside the building, they may say they are in the store (but they are also at the store).


"At" is used for location, while "in" is (generally) used to indicate being inside something.



Examples:



Q: Where did you buy your desk?
A: At Macy's. It's sold in the furniture department, on the third floor.


Q: (on the phone) Where are you? I can't see you in the parking lot. Are you at the front of the store?
A: I'm in the store, over by the electronics section.


Q: (texting) Where are you?
A: I had to get out of the house, so I'm in the park. I'm going by the coffee shop, and will be at your house in an hour.



Unfortunately there are many idiomatic usages. For example, you may be in a meeting, at (or on) the computer, in deep contemplation, at a loss, and many others.



methodology - Switching between levels, re-initialize existing structure or create new one?


This is something I've been wondering for quite a while. When building games that exist out of multiple levels (platformers, shmups etc) what is the prefered method to switch between the levels?


Let's say we have a level class that does the following:



  • Load data for the level design (tiles), enemies, graphics etc.

  • Setup all these elements in their appriopate locations and display them

  • Start physics and game logic


I'm stuck between the following 2 methods:


1: Throw away everything in the level class and make a new one, we have to load an entirely new level anyway!



2: pause the game logic and physics, unload all currents assets, then re-initialize those components with the level data for the new level.


They both have their pros and cons. Method 1 is alot easier and seems to make sense since we have to redo everything anyway. But method 2 allows you to re-use exisiting elements which might save resources and allows for a smoother transfer to the new level.




unity - Server logic on client side?



I am very confused by the PUN implementation of the Photon networking engine. It looks like I don't have to write a separate server so I'm very curious how this works. I have done quite some KryoNet developing and fiddled around with LidGren, these libraries require you to create a server and client.



  • The client sends minimum data to the server.

  • The server verifies this data and runs the gameplay logic from it.

  • The server sends back minimum data so the client can update to the current server state.


Since PUN does not allow me to write my own server how does PUN work? I believe there is a server behind PUN but if it's the clients job of verifying the data this is a vulnerability.


So whats the deal with Photon? Can a competitive game make use of PUN?



Answer



Alright, since this question seems like it was answered in the comments, let's turn that into an actual answer shall we?



Photon Unity 3D Networking (PUN) works by connecting people to each other instead of to a server for gameplay implementation. So, in short, it works with P2P networking. The most popular example I can think of is Call of Duty Modern Warfare series that uses this sort of (P2P) networking.


The biggest issue with this implementation is that the server is actually a player and should they cheat, it would be really hard to catch them (a reporting system would be necessary but since they have the server on their machine now, chances are, they could mask their username to something else).


The solution that Photon Engine offers is the Photon Server although this sort of P2P method could be used with other kinds of servers but it would take a bigger effort than using their own server implementation. Time versus money kind of deal.


Quote from the asker because these comments are also relevant to the answer itself:



You have to install Photon and run the server with it using the binaries. I guess these binaries get uploaded and started on the Photon cloud. They even seem to have a Unity api for this but the link to the documentation does not work.


Well, it does seem like PUN is not useful for a competitive game. It's an amazing framework to create something like Wordfeud or Hangman to play with your FB friends. But nothing that is even really competitive. I got Photon server working currently and it seems to have potential. But the price is kinda high if you compare it to something like KryoNet or Lidgren and pay to host it. I also dislike the development, on each change I need to build the server, put the binaries in a folder, restart photon and start the server again. Normally you would just run the server from your IDE.



Past simple vs used to vs would


I feel a little tangled in grammatical nuances and would like you to help me clear some things out. I know it's possible to use either the past simple, "used to" and "would" to talk about past habitual actions. But is the use of the last two of them limited only to personal experiences, or is it also correct to utilize them while talking about, say, historical events?


In other words: do these sentences mean exactly the same thing to you? Do you sense any differences between them?






  1. Jack the Ripper approached/would approach/used to approach his victims slowly and nonchalantly.




  2. The Aztecs fought/would fight/used to fight their enemies with wooden pikes.




  3. When he was a boy he practiced/would practice/used to practice playing piano.





  4. I read/would read/used to read a lot about astronomy even during my childhood.





I know a lot of such cases depend on the context; past simple can mean both a specific action and a series of repeated events, right? Oftentimes it's the words that create the meaning, not grammar, but does it apply to the utterances listed above?




Friday, January 22, 2016

How do I write a "Connect Four" AI?


I've made a Connect Four game. The first move is made by the player and the second by the computer. Currently, the computer moves randomly; its moves are generated by C++'s random number generator rand(). I'd like to build a basic AI that tries to win or prevent the player from winning.


How can I go about doing this?




How do I snap the Unity camera to a 2D, tile-based map?


I have a 2D, tile-based map. I want to be able to control the number of visible tiles on the screen vertically and horizontally, regardless of resolution. I want the player to be able to move the camera one tile width at a time until it hits the edge.


I do not understand how to manipulate the Unity camera in order to accomplish this. I have read the documentation, and Googled, but there is just something that is not clicking for me.


So, let's say I have a 100x100 map. A 32x24 portion of the map is shown at a resolution of 1024x768, each tile has a size of 1x1 Unity unit. The bottom-left of the visible area of the map starts at the bottom-left of the map (0, 0). The player then clicks the right arrow key and the map moves one tile to the right (1, 0).


How do I accomplish this, given that I am using the latest version of Unity in 2D mode?




android - How to make Box2D bodies automatically return to a initial rotation


I have two long Box2D bodies, that can collide while moving one of them around with MouseJoint. I want them to try to hold their position and rotation.


box 2d illustration



  1. Blue body is moved using MouseJoint (yellow) towards the Red body. Red body has another MouseJoint - Blue can push Red, but Red will try to return to the start point thanks to the MouseJoint - this works just fine.

  2. Both bodies correctly rotate along the middle. This is still as I want. I change the MouseJoint to move the Blue away.

  3. What I need is both bodies return to their initial rotation (green arrows)


  4. Desired positions and rotations


Is there anything in Box2D that could do this automatically? The MouseJoint does that nicely for position. I need it in AndEngine (Java, Android) port, but any Box2D solution is fine.


EDIT: By automatically I mean having something I can add to the object "Paddle" without the need to change game loop. I want to encapsulate this functionality to the object itself. I already have an object Paddle that has its own UpdateHandler which is being called from the game loop. What would be much nicer is to attach some kind of "spring" joint to both left and right sides of the paddle that would automatically level the paddle. I will be exploring this option soon.




Thursday, January 21, 2016

c# - Why does Unity use reflection to get the update method?


Why does Unity use reflection in order to access MonoBehaviour message methods like Awake, Update, Start,...?


Wouldn't it be slow to use reflection? Why doesn't it leverage other approaches like Template Method? It could simply define the methods as abstract in MonoBehaviour base class and force the subclasses to implement it.



Answer





How Update is called


No, Unity doesn’t use System.Reflection to find a magic method every time it needs to call one.



Instead, the first time a MonoBehaviour of a given type is accessed the underlying script is inspected through scripting runtime (either Mono or IL2CPP) whether it has any magic methods defined and this information is cached. If a MonoBehaviour has a specific method it is added to a proper list, for example if a script has Update method defined it is added to a list of scripts which need to be updated every frame.


During the game Unity just iterates through these lists and executes methods from it — that simple. Also, this is why it doesn’t matter if your Update method is public or private.



As for the reasons it is done this way, I'll largely refer you (the reader) to DMGregory's answer, which boils down to a balance of two competing things:



  1. Performance optimization

  2. Ease of new developer utilization


A new developer just wants it to Work and doesn't want to have to figure out "how do I connect this in to the event system?" but it should still run fast with minimal overhead.


The solution is probably the best that can be achieved within these two constraints. Or at least, the best the Unity dev team was able to come up with at the time. We may never know.



Can I write plugin/extension to Unity editor?


Is there possiblity to write my own plugin/extension to Unity editor ? I want to write plugin to generate map for me from xml file.



Answer



"Plugins" in Unity nomenclature mean native code (read: written in C/C++/Objective-C) DLLs. For what you want to do you more than likely don't need (or want, really) to use plugins.


For extensions, the Unity editor is very scriptable.



Are you asking if you can



  1. Populate a unity scene at editor time from an XML file

  2. Replace unity's default scene format entirely with an xml file.


Either way, what you're asking is more than possible. Here's an example of somebody completely replacing Unity's binary scene file format with a text representation: https://github.com/terravision/UnityTextScene


What you probably want to do is more likely just take advantage of their editor scripting tools. For example, look at ScriptableWizard. You can take that base code and then do something like load an XML file and spawn a bunch of prefabs, or whatever.


Pretty much the vast majority of things you see in the editor is scriptable. You can attach components, move/rotate/scale things, spawn prefabs, edit materials, all sorts of things.


difference - When to use "no" and "not"


I am stuck with this sentence:



There is no any reason to use it



In some contexts it's pretty clear which of the two words to use. But another, like the example above, is confusing me. So how would I say it: "no any reason" or "not any reason"?



Answer



You'd have to say one of these two:




There is not (isn't) any reason for you to do that.



or



There is (There's) no reason for you to do that.



Many EFL students say "no any", but it's always incorrect in all dialects of English.


phrase usage - Into and out of 'time out' for kids


Interested in the language of this disciplinary technique, I read on the Internet that children can be in time out but I was also looking for how to tell a child that they are in time out and when they are done their time out.


So how would you say just that in both Englishes across the pond. An example would be very appreciated in order to show how to use the word/phrase/sentence in both cases.



Answer



In the UK, the term the naughty step- the bottom step of the stairs- is often used. This term is much easier to use in conversation. You can say that a child is on the naughty step, off the naughty step, you can tell a child to go to the naughty step or to get off the naughty step.


This document uses the term "time in" for the state of not being in time out, but it appears in apostrophes which suggests that they do not consider it to be a real term.


This guide suggests that you can release a child by saying




You're being quiet, so you may come out of time out now



Many, however, feel that this casts the parent in the role of jailer. Other guides like this one therefore recommend going to the child at the end of the time out and reminding them why they were placed on time out, then telling them they need to say sorry for their behavior. When they do apologize, the parent is nice to the child and does not mention the time out again.


Wednesday, January 20, 2016

Meaning of "ain't" in: "...we ain't know what it meant"


What is the meaning of the following line:




We ain't know what it meant



Putting ain't = aren't doesn't make sense. I'm left with putting ain't = haven't, but have requires the third form of know, which is known, and is not the case. If I put ain't = don't then it makes sense,



We don't know what it meant



But the dictionary doesn't say that ain't = don't. So please explain me the meaning of that line.


Thank you.



Answer





What is the meaning of the following line:



We ain't know what it meant




If you do a google search for 'we ain't know' you get quite a lot of returns for the phrase in a context in which didn't fits nicely.


These include:


1



We was young, we was dumb, we ain't know what was doing. But now that we older, older. Lets take these things slower, slower. Reset the button, button




2



And we ain't know just what he had in store. But now here we are ten years later, flows got greater. Bonds got closer, plus it's more haters



A lot of these uses of 'We ain't know' are in other rap songs. Rap has its own vocabulary.


In addition Wikipedia states:



some speakers of AAVE [African American Vernacular English] also use ain't instead of don't, doesn't, or didn't (e.g., I ain't know that).




Thus:
3



We ain't know it 'til General Wheeler come thru and tell us. After that, de massa and missus let all de slaves go 'cepting me; they kept me to work in de house and ...



That seems to clear the matter up, since didn't fits the context of the rap song "Yellow Brick Road" by (Eminem).


Here is the opening part of Verse 3 of the song:



My first year in 9th grade, can't forget that day at school
It was cool till your man MC Shan came through

And said that Puma's The Brand 'cause the clan makes troops
It was rumors but man, god damn, they flew
Must've been true because man we done banned they shoes
I had the new ones the Cool J, Ice land swayed too
And we just through them in the trash like they yesterday's news
Guess who came through next, X-clan debut
Professor X vanglorious exists in a state of red, black, and green
With a key sissies now with this being a new trend
We don't fit in crackers is out with Cactus albums
Blackness is in, African symbols and medallions

Represents black power and we ain't know what it meant
Me and my man Howard and Butter, we would go to the mall with 'em
All over our necks like we're showing 'em off not knowing at all
We was being laughed at you ain't even half black
You ain't supposed to have that homie let me grab that
And that Flavor Flave clock we gonna have to snatch that



Again, ain't fits perfectly as didn't.


The song is an auto-biographical narrative in which Eminem hearkens back to his first day(s) in 9th grade (a grade he failed twice before dropping out of high school) and remembering various events and moments. Not surprisingly an important topic is brands of athletic shoes, including Puma.


Eminem is a cracker, semi-offensive slang for a poor white boy. He attends a school with lots of black students. They make fun of Eminem when he and his friends wear African symbols and medallions. In the middle of this Eminem says we ain't know what it meant.



Ain't occurs 5 times in the song. All five instances are in Verse 3.


For those interested, here is youtube version that has the lyrics scroll as they are recited. There are a few mild-ish swear words. Stanza 3 begins right after the repeated chorus at 2:57.




Last, while I was pondering this question, I wrote the following section. It does not seem as relevant now, but I'm including it so that it wasn't a wasted effort. It also shows that you cannot always trust dictionaries. But then again, I've never been impressed with the ODO.


Ain't usually signifies




  1. a negative form of to be





  2. the negative form have not / has not




(Note: One of the ODO's examples for has / have not actually means aren't. This is the first example under 1.1 "More Example Sentences". In this example 'Baseball's origins ain't found till they're found', ain't means aren't. Not only is this clear from the clause itself; but the title is an allusion to the famous axiom of former New York Yankee catcher Yogi Berra: 'It ain't over till it's over.' In which ain't also signifies the verb to be. In English, axioms are stated in the present tense.)


graphics programming - What are the advantages of tangent space normals over object space normals?


What are the advantages of normals in tangent space to normals in object space for calculation of bump mapping?



Answer



Everything, really.


The only benefit to object-space normals is simplicity. They're easier to use.


Tangent-space normals require a tangent-space basis, but offer:




  1. The ability to use the same texture for different surfaces. Object-space normal maps can only ever be used on the surface for which they were created. By regularizing normals in tangent-space, you gain the freedom to use the same bump texture for different surfaces. As long as the surface has a tangent-space basis, you'll get reasonable results.





  2. The ability to modify the texture mapping, with UV animation for example. Since object-space normal maps store normals in object-space, you can't just add 0.5 to all of the texture coordinates and expect to get proper normals from the texture. You can with tangent-space bump mapping.




  3. Smaller component representation. Object-space normal maps must have 3 components; you can't drop one and reconstitute it in the shader. Tangent-space normals will always have a positive Z component, so you can only store the XY of the normal. So you can either get greater precision by using a GL_RG16_SNORM or GL_RG16F formats (32-bits per texel), or employ compression by using an RG-compressed image format (GL_COMPRESSED_SIGNED_RG_RGTC1​, 8-bits per texel) format. You can try to use S3TC on an object-space normal map, but good luck with what you get back.




The absolute most you get with object-space normal maps is less computation time (not having to transform the light direction into tangent space, or alternatively, transforming the normal from tangent space into model space). But that's not a big deal, especially nowadays with deferred renderers running around.


unity - Finding Game Object with Regular Expressions


Is there a way to use a Regular expression in the GameObject.Find() method?


I'm making a checkers game and I've got pieces named Red Piece (x,y) and White Piece (x,y) (where x & y are actual integer coordinates). I want to destroy a piece at a certain x,y. So what I'm trying to do is something like


Destroy(GameObject.Find(Regex.Matches("(Red)|(White) Piece (" + x + ","+ y + ")")));

I need it to find any object with a name that contains "Piece (x,y)" whether it's a red piece or a white piece, and destroy it. Any ideas?





optimization - Chunking/caching large levels in a singleplayer game


Does it make sense to try to offload a large nonlinear level into file-based chunks, and load those on demand? We've implemented level chunking to improve rendering performance, but still all level objects are persistent in RAM.


If yes, then how do we keep the illusion of a living/changing world? Since the level is not linear, but rather like a world in itself, we cannot just pretend that whatever one's gone through is gone forever.



Is it a better idea to make the levels complex enough, but also optimized enough to be always persistent in memory, but implement micro/macro jump points which allow one to jump to a totally distant point (i.e. a whole new level), thus forgetting about the world consistency, and the illusion of a changing world. Also, this would allow us to follow a slightly linear story in a seemingly non-linear world. It would be possible to just apply a new state to the existing state of a "distant" level, if we are to bring the player back to it.




algorithm - Auto-organized / smart inventory system?


for the past week I've been working on an inventory system with Unity3D. At first I got help from the guys at Design3 but it wasn't too long till we split path, because I really didn't like the way they did their code, it didn't have any smell of OOP whatsoever.


I took it further steps ahead - items take more than one slot, advanced placement system (items tries their best to find the best close fit), local mouse system (mouse gets trapped in active bag area), etc.


Here's a demo of my work.


What we would like to have in our game, is an auto-organizing feature - not auto-sort. We want this feature because our inventory's going to be in 'real-time' - not like in Resident Evil 1,2,3 etc where you would pause the game and do things in your inventory. Now imagine your self in a sticky situation surrounded by zombies, and you don't have bullets, you look around, you see that there are bullets nearby on the ground, so you go for them and try to pick them up, but they don't fit! you look at your inventory and find out that if you reorganize some of the items, it will fit! - now the player - in that situation doesn't have time to reorganize because he's surrounded with zombies and will die if he stops and organizes the inventory to make space (remember inventory in real-time, no pausing) - wouldn't it be nice for that to happen automatically? - Yes!


(I believe this has been implemented in some games like Dungeon siege or something, so sure it's doable)


take a look at this picture for example:


What auto-sorting does


Yes, so if you auto-sort the issue you will get your spaces but it's bad because: 1- Expensive: it doesn't need a whole sort operation to free those spaces, in the first picture, just slide the red item at the bottom to the very left, and you get the same spaces that you got from the auto-sort. 2- It's annoying to the player: "Who the F told you to re-order my stuff?"


I'm not asking for "How to write the code" for this, I'm just asking for some guidance, where to look, what algorithms are involved? Is this something related to graphs and shortest path stuff? I hope not cuz I didn't manage to continue my college studies :/ But even if it is, just tell me and I will learn the stuff related.



Notice there could be more than just one solution. So I guess the first thing I have to do is figure out if the situation is 'solvable' - if I know how to determine if a situation is solvable or not, then I can 'solve' it. I just need to know the conditions that makes it 'solvable'. And I believe there must be some algorithm/data structure for this.


Here's a pic for more than one solution of trying to fit a 1x3 item:


enter image description here


The arrows show just one of the solutions, but if you look you will find more than one. This is what I ultimately not auto-sorting but find a solution and applying it.


Note that if I spend time on it I will come up with a way to solve it, but it wouldn't be the best way, it's like, holding a car wheel with your feet instead of your hands! XD Or just like trying to solve an issue that requires arrays, but you're not yet aware of their existence! So what is the right approach to this?


Updates from Commentary


@Stephen I'm really no guru in Alogs, you mentioned 'knapsack' and @BlueRaja - Danny Pflughoeft mentioned a 2D bin packing algo. Are they somehow related/same? - I'm still confused as to how should I approach this.


And yes I'm already using a "heuristic" but I didn't really know that I was :D it finds the first available slot, and see if the item fits there.


I don't know if ordering items based on their "bulkiness" (which I call nSlotsRequired=nRowsReq*nColsRec) would work, because you have a 2x2 and 1x4 items for example, they have the same bulkiness, but different shapes and will have a different effect on how the rest of the items next will go. SO... :/


I watched this video, I really liked the full packing idea, but I wonder how to go about it since the inventory is 2D. I'm not even sure that bin packing is the key here because, well it's true that I can have more than one bag, but in our game it's just gonna be one bag. So, it's a matter of fitting items in 'one' bag and not more than that. So the examples in that vid (the pipes and buses) don't really match with my problem. Also watched some stuff about this knapsack thing, I didn't see how the 'value' is related to my items/inventory, but I guess 'weight' is the same as bulkiness, not sure.





Tuesday, January 19, 2016

opengl - How can I convert a mouse click to a ray?


I have a perspective projection. When the user clicks on the screen, I want to compute the ray between the near and far planes that projects from the mouse point, so I can do some ray intersection code with my world.


I am using my own matrix and vector and ray classes and they all work as expected.


However, when I try and convert the ray to world coordinates my far always ends up as 0,0,0 and so my ray goes from the mouse click to the centre of the object space, rather than through it. (The x and y coordinates of near and far are identical, they differ only in the z coordinates where they are negatives of each other)



GLint vp[4];
glGetIntegerv(GL_VIEWPORT,vp);
matrix_t mv, p;
glGetFloatv(GL_MODELVIEW_MATRIX,mv.f);
glGetFloatv(GL_PROJECTION_MATRIX,p.f);
const matrix_t inv = (mv*p).inverse();
const float
unit_x = (2.0f*((float)(x-vp[0])/(vp[2]-vp[0])))-1.0f,
unit_y = 1.0f-(2.0f*((float)(y-vp[1])/(vp[3]-vp[1])));
const vec_t near(vec_t(unit_x,unit_y,-1)*inv);

const vec_t far(vec_t(unit_x,unit_y,1)*inv);
ray = ray_t(near,far-near);

What have I got wrong? (How do you unproject the mouse-point?)



Answer



I recently had to solve this myself for a WebGL application. I've attached the complete source code, but incase it doesn't work right off the bat for you here are some debugging tips:



  1. Don't debug your unproject method in your game. If possible, try to write unit-test style tests to make it easier to isolate what is going wrong.

  2. Be sure to print the output rays for both the near and far clipping planes.

  3. Remember that matrix math is NOT commutative. A x C != C x A. Double check your math.



Also, to reply to some comments above, you almost never want to use OpenGL's selection APIs. That helps you pick existing items, like if you were creating a menu, however it fails to perform most real-world scenarios like 3D model editing. Where you need to add geometry as a result of the click.


Here is my implementation. There is nothing magic going on here. Just JavaScript and Google's Closure library.


gluUnProject


/**
* Port of gluUnProject. Unprojects a 2D screen coordinate into the model-view
* coordinates.
* @param {Number} winX The window point for the x value.
* @param {Number} winY The window point for the y value.
* @param {Number} winZ The window point for the z value. This should range

* between 0 and 1. 0 meaning the near clipping plane and 1 for the far.
* @param {goog.math.Matrix} modelViewMatrix The model-view matrix.
* @param {goog.math.Matrix} projectMatrix The projection matrix.
* @param {Array.} view the viewport coordinate array.
* @param {Array.} objPos the model point result.
* @return {Boolean} Whether or not the unprojection was successful.
*/
octorok.math.Matrix.gluUnProject = function(winX, winY, winZ,
modelViewMatrix, projectionMatrix,
viewPort, objPos) {

// Compute the inverse of the perspective x model-view matrix.
/** @type {goog.math.Matrix} */
var transformMatrix =
projectionMatrix.multiply(modelViewMatrix).getInverse();

// Transformation of normalized coordinates (-1 to 1).
/** @type {Array.} */
var inVector = [
(winX - viewPort[0]) / viewPort[2] * 2.0 - 1.0,
(winY - viewPort[1]) / viewPort[3] * 2.0 - 1.0,

2.0 * winZ - 1.0,
1.0 ];

// Now transform that vector into object coordinates.
/** @type {goog.math.Matrix} */
// Flip 1x4 to 4x1. (Alternately use different matrix ctor.
var inMatrix = new goog.math.Matrix([ inVector ]).getTranspose();
/** @type {goog.math.Matrix} */
var resultMtx = transformMatrix.multiply(inMatrix);
/** @type {Array.} */

var resultArr = [
resultMtx.getValueAt(0, 0),
resultMtx.getValueAt(1, 0),
resultMtx.getValueAt(2, 0),
resultMtx.getValueAt(3, 0) ];

if (resultArr[3] == 0.0) {
return false;
}


// Invert to normalize x, y, and z values.
resultArr[3] = 1.0 / resultArr[3];

objPos[0] = resultArr[0] * resultArr[3];
objPos[1] = resultArr[1] * resultArr[3];
objPos[2] = resultArr[2] * resultArr[3];

return true;
};


Usage


  this.sys.event_mouseClicked = function(event) {
// Relative x and y are computed via magic by SystemModule.
// Should range from 0 .. viewport width/height.
var winX = event.relativeX;
var winY = event.relativeY;
window.console.log('Camera at [' + me.camera.position_ + ']');
window.console.log('Clicked [' + winX + ', ' + winY + ']');

// viewportOriginX, viewportOriginY, viewportWidth, viewportHeight

var viewPort = [0, 0, event.viewPortWidth, event.viewPortHeight];
var objPos = []; // out parameter.

// The camera's model-view matrix is the result of gluLookAt.
var modelViewMatrix = me.camera.getCameraMatrix();
// The perspective matrix is the result of gluPerspective.
var perspectiveMatrix = pMatrix.get();

// Ray start
var result1 = octorok.math.Matrix.gluUnProject(

winX, winY, 0.0,
modelViewMatrix, perspectiveMatrix,
viewPort, objPos);
window.console.log('Seg start: ' + objPos + ' (result:' + result1 + ')');

// Ray end
var result2 = octorok.math.Matrix.gluUnProject(
winX, winY, 1.0,
modelViewMatrix, perspectiveMatrix,
viewPort, objPos);

window.console.log('Seg end: ' + objPos + ' (result:' + result2 + ')');
};
};

unity - Smooth Camera Follow


I am using a fixed static background. I have a gameobject(Current ref. image) which is moving with the help of waypoints. I have made camera to follow the Current. The camera is stuttering while moving. Can anyone help me to solve the camera stuttering and make it follow the Current smoothly?


This is my code attached to camera following the star


public class CameraController : MonoBehaviour {

void Start () {
GameObject.FindGameObjectWithTag("OptionCamera").GetComponent().orthographicSize =
(20.0f / Screen.width * Screen.height / 2.0f);

}

void LateUpdate() {
if (GameObject.FindGameObjectWithTag ("Current") != null) {
if (GameObject.FindGameObjectWithTag ("Current").GetComponent().Greenblast == false &&
GameObject.FindGameObjectWithTag ("Current").GetComponent().Redblast == false)
{
Vector3 pos = GameObject.FindGameObjectWithTag ("Current").transform.position;
transform.position = new Vector3 (transform.position.x, pos.y, transform.position.z);
}

}
}
}

Example of Camera movement




conjunctions - until VS. before


When you are to choose between two conjunctions, ˜until' and ˜before" for the following sentences, which is more natural?




  1. Most children do not start school ( until, before) they are six years old.


  2. Jake live in N.Y. (until, before) he was thirty years old, and then he went to LA.


    To me, ˜until' sounds better for both sentences, but ˜before' doesn't sound bad either. Any comments would be appreciated.


    Sentence 1, which has a negative verb, is natural with either form. "BEFORE they are six years old" implies that they do not start at any point in time before their sixth birthdays. "UNTIL they are six years old" states a condition "” "be six years old" "” that must be fulfilled. Either statement is OK.


    Sentence 2 is a bit more complicated. If Jake lived in N.Y. UNTIL he was thirty years old, he went to L.A. as soon as he turned thirty. If you say only "Jake lived in N.Y. BEFORE he was thirty," technically Jake could have lived in New York and in many other places before he was thirty. You could say "Jake lived in Stockholm, Beijing, Istanbul, and New York before he was thirty." But this sentence makes it clear that there was no time interval between his living in New York and his going to L.A., because it states "...and THEN he went to L.A." Apple's sentence is therefore unambiguous with BEFORE because of the adverbial clause "THEN he went to L.A."




..................



One of my friends has provided the explanations. I am, however, confused with the bold parts, that is, does the preposition "until" make a condition??


What is more, I failed to get the bold parts at all.




Monday, January 18, 2016

html5 - 2D maps, how to structure?


I'm new to this. And I don't really understand 2D tile maps.


The tutorials I've read use arrays, but doesn't this get really difficult to manage when they get big?


And what if I want different floors, like going up/down stairs, do I need an array for every "level" of the game world?



Could anyone explain tile based maps as simple as possible please? If you include code, please make it Javascript or pseudo code since it's all i know.



Answer



2D tile maps are exactly how they sound, imagine something like this:


1,1,1,1,1
1,0,0,0,1
1,0,2,0,1
1,0,0,0,1
1,1,0,1,1

This the design of our map and if we take



0 = floor
1 = wall
2 = chest

Then you can see that our map is a room with an entrance and a chest in the middle of the room our data structure for this could be like @georgeK said an Array of arrays ie.


var map =[ [1,1,1,1,1],
[1,0,0,0,1],
[1,0,2,0,1],
[1,0,0,0,1],
[1,1,0,1,1]];


We would then load each of our tiles into a look up just the once and draw our room by putting that tile in place of the number on the grid.


for row in map
for each cell in row
draw tile offset by the x, y position in the array multiplied by tile width.
end inner loop
end outer loop

Now you may not wish to draw this to the canvas directly and instead draw to a off DOM canvas and then transfer the entire image at once.


As a side note a 2d map based in html 5 has been done by google as proof of concept for a multiplayer game which could give you a few ideas on optimization. video here



Hope this helps


movement - How to move the ball in straight line in gamesalad?


I have an actor named ball and I want to move it in a straight line which is created by actor ball's X and Y coordinate and cursor's X and Y coordinate. I have Move To behavior in gamesalad but I don't have exact idea how to move the ball with two Cartesian coordinates ball and cursor.





c++ - I am looking to create realistic car movement using vectors


I have goggled how to do this and found this http://www.helixsoft.nl/articles/circle/sincos.htm I have had a go at it but most of the functions that were showed didn't work I just got errors because they didn't exist. I have looked at the cos and sin functions but don't understand how to use them or how to get the car movement working correctly using vectors. I have no code because I am not sure what to do sorry.


Any help is appreciated.


EDIT:


I have restrictions that I must use the TL engine for my game, I am not allowed to add any sort of physics engine. It must be programmed in c++. Here is a sample of what i got from trying to follow what was done in the link I provided.


if(myEngine->KeyHeld(Key_W))
{

length += carSpeedIncrement;
}
if(myEngine->KeyHeld(Key_S))
{
length -= carSpeedIncrement;
}
if(myEngine->KeyHeld(Key_A))
{
angle -= carSpeedIncrement;
}

if(myEngine->KeyHeld(Key_D))
{
angle += carSpeedIncrement;
}

carVolocityX = cos(angle);
carVolocityZ = cos(angle);

car->MoveX(carVolocityX * frameTime);
car->MoveZ(carVolocityZ * frameTime);



Sunday, January 17, 2016

grammaticality - "Not they" or "not them"




  1. You, not them, are responsible for that.

  2. You, not they, are responsible for that.



Which one is correct? And why?




Saturday, January 16, 2016

Problems using easing equations in C# XNA


I'm having some trouble using the easing equations suggested by Robert Penner for ActionScript (http://www.robertpenner.com/easing/, and a Flash demo here) in my C# XNA game. Firstly, what is the definition of the following variables passed in as arguments to each equation?


float t, float b, float c, float d

I'm currently calculating the new X position of a sprite in the Update() loop, however even for the linear tween equation I'm getting some odd results. I'm using the following values:


float t = gameTime.TotalGameTime.TotalMilliseconds;
float d = 8000f;
float b = x.Position.X;

float c = (ScreenManager.Game.GraphicsDevice.Viewport.Width >> 1) - (x.Position.X + x.frameSize.X / 2);

And this equation for linear easing:


 float val = c*t/d + b;

Answer




Firstly, what is the definition of the following variables passed in as arguments to each equation?



The answer was in the link you provided:




  • t = current time (starting from 0 and increasing up to the chosen duration)

  • d = duration (i.e. total time of the animation)

  • b = initial value

  • c = change in value (i.e. how much the value should change, or the difference between the final value and the initial value)


Now for your troubles. Let's take a look at the values you chose for t and d:


float t = gameTime.TotalGameTime.TotalMilliseconds;
float d = 8000f;

I'm guessing you want your interpolation to take 8 seconds to complete, i.e. 8000 miliseconds. In that case the value of t should be starting a 0 on the first frame of the interpolation, and increment a little each frame until it reaches 8000, at which point you should stop updating because the interpolation is complete.



The problem is that you're passing it the value of gameTime.TotalGameTime which is the time that has passed since the game began, and you're supposed to pass it the time that has passed since the animation has begun. Here's the proper solution. First:


// Once at the start of the animation
// Note: I'll also use seconds instead of miliseconds
float t = 0f;
float d = 8f;
bool animating = true;

And then:


// Then once for each frame while the animation is active (i.e. in Update)
if(animating)

{
t += gameTime.ElapsedGameTime.TotalSeconds;

// Don't let time exceed the duration
t = MathHelper.Min(t, d);

// Calculate your "val" here
float val = b + t/d * c;

// Stop animating if we've reached the end

if(t >= d)
animating = false;
}

As for your other values, the value of c looks really cryptic and I'm not really sure what you're trying to do. But basically in this given context, c should be the amount of units you want your character to move.


Finally, unless you're trying to do some really fancy easing, I would just use one of the XNA's built in methods for this:



android - Centering GLViewport position within physical screen


I'm developing my app on one device and want it to display at the same ratio on all other devices.


Currently what I have is 'image 1' in my image below - the game fits perfectly onto my development device's screen.


If I keep the viewport at the same ratio then I get the results seen in 'image 2'.


This is great, but now I need to center the viewport , and I'm not sure how to do that.


What I'm aiming for is what is in 'image 3' - just not sure how to get there.


This is how I'm keeping the viewport at the same ratio:


the ratio is width / height (this is 1.702127659574468 and we will use this explicitly)


//Set viewport size based on screen dimensions      

GLES20.glViewport(XVal, YVal, (int) (height * 1.702127659574468), height);

At the moment, XVal and YVal are both 0 - I need to change XVal to move the image along.


How do I work out the amount to move the viewport along by? (I know it will be equal to half of the space to the right of the viewport ('image 2') - just not sure how to work this out.......)


enter image description here



Answer



xoffset = (targetScreenWidth - image1Width)/2;

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