Sunday, September 30, 2018

difference - different vs differential (adjectives, not nouns)





  1. ODO doesn't distinguish them, except calculus's definition about which I'm not asking. ''different' is synonymized with 'differential', and vice versa.




  2. Why can't 'different' substitute 'differential' in the red underlines beneath?




Source: Introduction to Politics: First Canadian Edition (2012 1 ed., but ∃ 2016 2 ed.). p. 87 Top


enter image description here




  From the right, Rawls's major critic has been the American philosopher Robert Nozick (1938—2002). Nozick was writing from a libertarian perspective, which calls for a state focused on protection of property rights. He put forward a procedural theory of justice in which the main concern is not the outcome (e.g., meeting needs) but the way in which property (in the broad sense, meaning anything possessed by an individual) is acquired. It is therefore a historical theory in which "past circumstances or actions of people can create differential entitlements or differential deserts to things" (Nozick, 1974, [Anarchy, State, and Utopia]: p. 155). Provided that the property was acquired fairly, then the owner has a just entitlement to it. Nozick considered any attempt to redistribute property, even through taxation, to be unjust.





Article "a" with uncountable nouns


There is such a thing in English that when a mass noun combined with an adjective it takes the indefinite article. For example:



He had a great knowledge of English.



But I have noticed that is not always the case. For example: I have observed that with the word "fluency" and other adjective the is not followed, for instance:



She showed great fluency in English.




Would it be correct to say "She showed a great fluency in English"? Tell me please if there is any additional rule to that.



Answer



There is a rule in Michael Swan's "Practical English Usage" (section 149.4):



With certain uncountable nouns – especially nouns referring to human emotions and mental activity – we often use a/an when we are limiting their meaning in some way (and we generally limit it by putting adjectives).



  • We need a secretary with a first-class knowledge of German (NOT...with first class knowledge of German ).

  • She has always had a deep distrust of strangers.

  • That child shows a surprising understanding of adult behaviour.

  • My parents wanted me to have a good education (NOT .... to have good education).


  • You've been a great help.

  • I need a good sleep.


Note that these nouns cannot normally be used in the plural, and that most uncountable nouns cannot be used with a/an at all, even when they have an adjective.



  • My father enjoys very good health. (NOT ... a very good health.)

  • We are having terrible weather. (NOT... a terrible weather.)

  • He speaks excellent English. (NOT ... an excellent English.)

  • It's interesting work (NOT ... an interesting work.)




Unfortunately this book does't show a list of such uncountable nouns which can/cannot be used with "a". But the Ngram Viewer shows that "fluency" is not used with "a". See the results of searching:



So, it would be better to say "She showed great fluency in English".


legal - Licensing (or similar) for my fan-game?


For the past 8 years, I've been working on a Pokémon fan-game. It's been awesome, well-received by players, and I'm very proud of the community we've built. But, as with all things "fan-game", there's always that looming grey cloud of "will a C&D arrive tomorrow?"


Now, I've taken some steps to ensure we're as respectful as possible towards Nintendo's property:



  • We stay as true as possible to the source material. While we have added our own variants and original characters ("Fakemon"), we've made great efforts to keep them consistent.

  • We make it clear that we are a fan-game, not affiliated with Nintendo, and that it is entirely unofficial. I also include a link to a shareholder Q&A (Q14) where Satoru Iwata confirmed that they are not interested in treating people like myself as criminals.

  • Our game concept is original. It's not a clone of any existing game, and I like to think it fills a nice little hole for fans of the series.

  • I (briefly) met C-level people from Game Freak and Nintendo, including Junichi Masuda and Tsunekazu Ishihara, and given them "business cards" for our game. However, it wasn't a formal meeting, rather they were signing autographs at the Pokémon World Championships, so for all I know I was probably just some fan and they didn't pay much attention to the card (they've got enough to do already, right?)



But, all that being said, we're still unofficial, using intellectual property that doesn't belong to us.


My friend and I quit our jobs to work on this game full-time. If we do get shut down, we're going to have to seriously struggle to put our lives back together. So for now, the game has mostly been kept "under the radar", with basically zero marketing and only word-of-mouth of players to keep it populated.


The biggest thing here is that I want to give back to Nintendo. Thanks to them, and to my project, I've made incredible progress as a developer, designer and just as a person in general.


As mentioned earlier, my biggest fear is that one day they'll shut us down. And we'd have no choice but to do so. But it's been 8 years now...


So I'm trying to figure out what options I have, if any. I think what I want to do is to reach out and ask about some kind of licensing, but I don't want to draw too much attention. I don't want to lift my head over the parapet only to have it blasted off, you know? I'm not looking for Pokémon GO levels of attention, or even Magikarp Jump. (Our single server would melt either way - I'm working on it!) Just some way of having actual "permission" to do what I'm doing.


I expect the answer will probably be along the lines of "IANAL, get one", but what kind of lawyer would be best? And any insights or advice besides that would be helpful too.




Saturday, September 29, 2018

unity - How does transvoxel algorithm work and how can I implement It?


After wasting over three days of researching on DuckDuckGo/Google, trying to understand transvoxel paper and existing implementation, I come here to clarify the subject for me and made it easier for the next person who wants to implement it.


Here is the transvoxel's homepage which explains well what the algorithm solves. So now I'm happy to find something that solves my current problem, so I would like to implement it to my code, but the website doesn't explain how to implement it or sharing code (except tables). So I was looking for existing implementation of the transvoxel algorithm:





  • Transvoxel (XNA): Looks great but this solution all-in-one (octree, caching, voxel, etc.) I really tried to understand the transvoxel class into this one, but no.




  • Transvoxel (OGRE3D): Looks great too but again, all in one. I tried too to understand, I translated the code from C++ to C#, but no again.




Finding for marching cube was so easy, one class copy&paste, one public function.


So I gave up the idea to use existing implementation. Why not implementing it myself? (Sadly I don't have the skill to fully understand what the paper said, for example the ambiguous case).


The first thing I didn't understand was if transvoxel is a modified marching cube or a seconds layer that modify the work of the marching cube. In the C++ code (second link of the list) the code uses a implementation of marching cube and transvoxelize each border, on the paper they talk about 19x19x19 voxel data on 16x16x16 chunk and about a modified version of marching cube.


So do you guys can explain me how the transvoxel algorithm works and how can I implement it on my existing project?



My existing project is an Unity3D project which uses marching cubes for an infinite world, LOD chunk are ready, the only one thing missing is fixing crack between different LOD level chunk.




physics - What are the properties of "position, velocity, acceleration, rotation" collectively named?


They say naming things is one of the hardest problems in computer programming. They were right.


Given the pseudocode below, what is a more appropriate name for this collection of properties? "Course", "Route", "Heading", "Orientation" all don't capture it.


class NewtonianStuff { // <-- Needs a better name
vec3 position, velocity, acceleration; // <-- What is this group called
quat rotation;
};


class SpaceShip {
NewtonianStuff xxxxxx; // <-- What do you call that
};

Perhaps that collection is too abstract. What is the formal name for this collection of properties?


vec3 position, velocity, acceleration;

The best I can come up with is "PositionAndDerivatives", which doesn't really flow.



Answer



The position and rotation (and scale) are generally referred to as the transform.



Velocity, acceleration, force, impulse, etc are usually just lumped together as "physics state" or "body" (which might also have handles to the shape of the physical object or any bounding shapes, or those might be part of a separate "collider"). I don't believe there is a formal name used in games for this collection of properties, especially as the properties used varies for each game / physics engines.


python - Collision detection performance problem


Using python and pygame I've built a collision detection system according to the instructions in this YouTube tutorial.


This is updated 40 times per second and controls movement and collision detection between some number of "agents", which are circles, each with a radius of 20:


for a in self.agents:
dir = a.target - a.pos

if dir.length >= 3:
dir.length = 3
a.pos = a.pos + dir


for a in self.agents:
for a2 in self.agents:
if a==a2: continue
d = a.pos.get_distance(a2.pos)
if d<40:

overlap = 40 - d
dir = a2.pos - a.pos
dir.length = overlap/2
a2.pos= a2.pos+dir
a.pos= a.pos-dir

This looks and works great, as long as the number of agents is below 100. A higher number of agents will cause the pygame frame rate to drop. I left out some code which increases movement speed and pushback for a selected agent, but I don't think it has any consequence for the issue.


How can I make the code more efficient? For instance, would it help to make it so agents only check the distance of other nearby agents, say within a circle 4X the size of the agent, instead checking the complete list in every iteration of the code. Or is it better to change the method all together?



Answer



You're checking each agent against every other agent more than once. For example, consider a simple list of 3 agents, there should only 3 checks, you're checking 9 times, and that gets much worse with larger numbers. At 100 you're checking 10,000 times instead of 5,050.



When you iterate like you're doing, the comparison happens like this:


A1->A1 //Ignored
A1->A2
A1->A3
A2->A1 //Already checked
A2->A2 //Ignored
A2->A3
A3->A1 //Already checked
A3->A2 //Already checked
A3->A3 //Ignored


You need to check against the agents using a for loop. The inner for loop should start just after the agent being checked in the outer for loop.


for (int i = 0; i < agents.size(); i++) {
for (int j = i+1; j < agents.size(); j++) {
//Test
}
}

The number of checks can be calculated by:


1+2+3+4+5+6+...+N-1


Otherwise written as:


(N(N+1)/2)-N

Its a Triangular number minus N (since we're cutting out the tests against self).


You should see significant improvements there, beyond that, spatial partitioning will help reduce the number of checks needed.


Friday, September 28, 2018

mathematics - Dynamic force behind logical jumping on 3 axis'


I've been working on physical jumping in a 3D environment, I've got it working with a static force. The problem with this is that the force on each axis should be different due to the rotation from the player.


A few things to keep in mind:



  • A total rotation of 360 degrees can be made;


  • Forces should never be greater than 0.2 or lower than -0.2;

  • There is no framework/engine behind the game, it's all hardcore codings.


I've been trying something like;


velocity.x = x - ( x + ( 10 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );
velocity.y = y - ( y + ( 20 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );

where x,y is the spawned location and rz is the rotation from the player. This way, I'll get the location from the player 20 units in front of him. By subtracting the actual starting position from it, I should've gotten a velocity. However, this turned out to be wrong. It's not going towards the direction the user is facing, it's just doing it's own simple thing.


The jumping/throwing into 1 direction is working perfectly fine. The calculations I made so far are totally messed up and not working as expected.


The results which I am expecting to get is something like;



force.x = 0.1;
force.y = 0.2;

this can be negative or positive, this should be dynamic though.



Answer



So first, in the formula:


velocity.x = x - ( x + ( 10 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );

The two 'x's cancel out each other:


x - (x + n)


is same as


x - x - n

Then to convert an angle to a vector you need to use sin AND cos.


velocity.x = speed * math.cos ( rz * math.pi / 180 );
velocity.y = speed * math.sin ( rz * math.pi / 180 );

In this case rz will indicate a counter-clockwise rotation if y increases vertically (clockwise if not), with 0 degrees being in the positive x direction (usually, to the right).


To have rz rotate the other way:



velocity.x = speed * math.cos ( rz * math.pi / 180 );
velocity.y = speed * math.sin ( rz * math.pi / -180 );

sentence construction - Missed who vs. Missed whom?


I play online multiplayer game clash of clan. Two native English speakers were talking with each other. The first one showed(appeared?) after some days, and then the other person said:



Missed who



The speaker is most probably from New Zealand; if not then Canadian for sure. What I am confused about is that I think the correct way should be to say, "Missed whom". I can think of sentences like:



  • I missed you.

  • I missed him.

  • I missed whom?


  • Whom did I miss?


The you, him, whom all are in object form. So, I think correct usage would be missed whom not missed who?


Is the who usage a vernacular, different figurative meaning, or actually the correct usage?




vocabulary - discerning between the usage of raise and rise?


I am wondering if there is any difference between the bold parts?



these are extracted from Longman:



rise: increase: to increase in number, amount, or value [= go up; ≠ fall]


raise: increase to increase an amount, number, or level [≠ lower]:




Answer



They do not always mean the same thing in different contexts. They are similar, yes, but they have different impacts on sentences. It takes a bit to figure out adequate usage but you'll get it sooner or later.


Your examples:





  • "Sales rose by 20% over the Christmas period" = The amount of sales increased by 20% over Christmas

  • "Many shops have raised their prices" = Many shops have increased the amount of their products, therefore increasing their prices



See, the examples you used have similar meanings but the word "raise" is commonly used in a context where it refers to an entity.


Watch my usage:





  • Upon asking him what he does for a living, the goat herder muttered "I raise livestock for my daily bread". (This usage focuses on the word raise referring to the growth or increase, yes, in size and not volume of an entity "livestock". It is not the same as any equivalent using the word "rise".





  • Watching the prices rise slowly was a nerve-wrecking experience for the stock broker. (This is focused on an increase in direct value in a quantitative sense). Not the same as an example of the word "raise"





I don't believe in dictionary definitions being the only way to use words in English but I would advise you to read the following links so you can understand a bit more of the usage and discern for yourself.



grammaticality - 'starting cleaning' vs 'starting to clean'


In an answer to this ELL question, one of our users provided this example sentence, claiming it was grammatical:



He sighed starting cleaning the floor.



That sentence seems to clash in my native ear. I suggested that it wasn't good grammar, and that (assuming I'm understanding the gist of the sentence) it should be restructure to something like:




He sighed, and started to clean the floor.



or



He sighed and started cleaning the floor.



In a comment, though, the user who wrote the sentence stuck by the claim that the original example sentence doesn't violate any grammatical rules.


Rather than start a protracted debate under the comments over there, I figured I would simply ask about the matter here in a new question.


Is this sentence acceptible from a purely grammatical standpoint? Is it colloquial?


I did find some sentences online that used the "starting cleaning" word pair, but they weren't really using them as consecutive verbs. For example:




A broom, mop, sponges, dish soap, hand soap, paper towels, and all-purpose cleaner should serve well as a starting cleaning package.



In this case, both starting and cleaning modify package adjectively, so, even though that sentence uses the two words, it's meaning and grammatical structure are quite different.


Should I retract my comment? Or keeping sticking [sic] to my guns?



Answer



Grammatical? —




  • Conventional orthography, whether mechanical or rhetorical, demands a comma after sighed. Is punctuation a matter of grammar? I dunno; but it's certainly a factor in intelligibility.





  • Starting cleaning is syntactically acceptable—start undoubtedly licenses gerund complements. But I think it would grate on most native hearers, because it violates the horror aequi principle. Is that a matter of grammar? I dunno; but it's certainly a factor in acceptability.


    ADDED following pointers from F.E., DamkerngT and Araucaria: Geoffrey Pullum and Arnold Zwicky (names to conjure with!), 'Gerund participles and head-complement inflection conditions', in Collins and Lee, The Clause in English: In honor of Rodney Huddleston, 1999, find an explicitly syntactic constraint: "It is not acceptable in most varieties of modern English for a complement (as opposed to an object) marked with gerund participle inflection to be adjacent to its matrix-clause verb when that verb is likewise in gerund participle form."




Just as there are lots of technically legal practices which honorable merchants will not perpetrate on their customers, there are lots of technically grammatical constructions which good writers will not perpetrate on their readers.


spelling - "Its" and "it's" - how to remember?


What is a good mnemonic rule that an English learner can use to remember the difference between its (possessive adjective: a team has started its lunch) and it's (verb: it's raining)?



Answer



I'm not sure of how good a mnemonic this is, but it's always worked for me. When proofreading, I simply remind myself:




You can't remove an apostrophe when it's taking the place of a letter.



So, when I say:



It's supposed to rain tomorrow.



I recognize that "It's" means "It is", so I leave the apostrophe in. But when I type and proofread:



The house is losing it's foundation. [sic]




I realize that "it's" does not mean "it is"; it means "the foundation belonging to it", so I remove the apostrophe:



The house is losing its foundation.



If you don't like my method, it's easy to find lots more on the subject.


vocabulary - Which one is correct: "my little brother" or "my smaller brother"?


If I'm 18 and my brother is 15, is he my little brother and I'm his elder brother? Or he is my smaller brother and I'm his bigger one?


Any clarifications?



Answer



When you want to be clear that the distinction is about age, the simplest and most obvious choice is, like Shaunak Sukla says:



younger brother, older brother



However, it is very common to refer to a younger sibling as little or an older one as big (usually not bigger!):




little brother, big brother



Although this refers to size, in practice it normally means the little one is the youngest. It is also used between grown-ups to indicate the (usually by then irrelevant) difference in age. It is even done jokingly, especially if the younger sibling has outgrown the older one.


sentence choice - Preposition Usage; "My interest in ~", "My interest about ~" or "My interest to ~"


I wonder which one of these is the best sentence.


Or, if they make different meaning in sentence, please explain it to me !


1. My interest in human right in North Korea has started from CNN documentary.
2. My interest about human right in North Korea has started from CNN documentary.

3. My interest to human right in North Korea has started from CNN documentary.

Thank you ! :)



Answer



The best answer is in. People have an interest in things. See the attached graph. It includes both the simple present (interest) and simple past (interested) forms. The number of uses of interest(ed) about things is so low that it is represented by just a line straight across the bottom of the graph. I did not include interest to because in your sentence that is not grammatical.


Examples include:


1 I am interested in human rights.


2 My interest in human rights began with...


3 He is interested in that woman...


enter image description here



If you want to use about, a common word used with it is curious or curiosity.


Examples include:


1 I am curious about human rights.


2 My curiosity about human rights began with...


3 He is curious about that woman...


british english - Can any time on clock be spoken as it is in numbers only (hour + minutes)?



According to the Cambridge dictionary, the answer for “What time is it?” depends on the minutes.



When the times outside five-minute intervals, we say minutes past or minutes to:


9.01 one minute past nine


9.03 three minutes past nine


9.36 twenty-four minutes to ten


9.58 two minutes to ten



Otherwise, we can say directly what we see on the watch / clock, it says to read it simply. For example:




9.05 five past nine or nine oh five


9.10 ten past nine or nine ten


9.15 quarter past nine or nine fifteen


9.20 twenty past nine or nine twenty


9.25 twenty-five past nine or nine twenty-five



Can we say times out loud by the actual numbers that are on the watch / clock and maybe these Cambridge rules are only in the UK? According to what I remember, many times when I asked people about the time, they didn't follow those rules. They would say: 10:13 = Ten thirteen. 8:21 = eight twenty one etc. If that is correct, then what about 10:11, 10:10, 9:11 — if I simply read them as they are (Ten eleven), it works?




game loop - Updating entities in response to collisions - should this be in the collision-detection class or in the entity-updater class?


In a game I'm working on, there's a class responsible for collision detection. It's method detectCollisions(List entities) is called from the main gameloop.


The code to update the entities (i.e. where the entities 'act': update their positions, invoke AI, etc) is in a different class, in the method updateEntities(List entities). Also called from the gameloop, after the collision detection.


When there's a collision between two entities, usually something needs to be done. For example, zero the velocity of both entities in the collision, or kill one of the entities.


It would be easy to have this code in the CollisionDetector class. E.g. in psuedocode:



for(Entity entityA in entities){
for(Entity entityB in entities){
if(collision(entityA, entityB)){
if(entityA instanceof Robot && entityB instanceof Robot){
entityA.setVelocity(0,0);
entityB.setVelocity(0,0);
}
if(entityA instanceof Missile || entityB instanceof Missile){
entityA.die();
entityB.die();

}
}
}
}

However, I'm not sure if updating the state of entities in response to collision should be the job of CollisionDetector. Maybe it should be the job of EntityUpdater, which runs after the collision detection in the gameloop.


Is it okay to have the code responding to collisions in the collision detection system? Or should the collision detection class only detect collisions, report them to some other class and have that class affect the state of the entities?




Thursday, September 27, 2018

phrase request - How does a native speaker express there is no problem except an error


Someone provided me a business document and asked me to check it and I have found an error.


If i want to point out the error, how would a native speaker express "there is no problem except this one I found"?




grammar - Why do I have to say “want you to do” instead of “want you do”?


I'm confused about 'want you to do (something)' and 'want you do (something)'.


Example:



"I want you to eat fish" instead of "I want you eat fish" or "I want that you eat fish".




Can anyone explain what is the grammar rule for this?




Unity: cg fragment shader processing array of points


I need to write a fragment shader which would somehow be aware of N points that are in the scene and darken pixels based on their world coord distance to the points. I'm looking for a method that would be still suitable for mobile devices. I image I could pass the points as a texture but i'm stuck in figuring out how to effectively evaluate if a pixel is close enough to any of the N points (I know how to do this for 1 point, but for N without a loop?). Any ideas if this is doable in a performance efficient manner? All ideas are welcome. Thanks!


enter image description here



Answer



As discussed in the comments above, it may be easier to get this effect (and scale better to large values of N) by flipping the request around.


Rather than the shader for the scene geometry checking - in every rendered fragment - its distance to each of the N points, we can instead draw the scene geometry normally, then "stamp" the effects onto it by rendering some triangles for each of the N points.



This is effectively the same flip in thinking we do when moving from forward lighting to deferred. If each light/point's effect area is small (ie. less than the full screen) and there are many of them, we can reduce redundant work this way.


So, that leaves a few choices for how to render your points' effects:


1. Shadow quads


The images you've shown look a lot like blob shadows in older 3D games. If this is representative, that the blobs will always fall on some plane in a defined direction ("down"), we can do this very cheaply with no depth tricks:


In a CPU-side (C#/UnityScript) script, raycast down from each of your N points to find the nearest surface in that direction. Then position a quad at that position, scaled appropriately for how wide your effect is meant to be at that distance. Use a shader on the quad that will decal your desired effect onto the surface.


2. Deferred decals/ screen-space decals


This is the way to go if you want either an omni-directional effect, or one that shines "though" the first surface it encounters so it can affect multiple at once, or if the surfaces it's affecting are bumpy & irregular, hard to cover with a single quad. But it's much more complicated, so if you're not in one of these situations, you're probably better off using a quad.


The idea is to position a mesh representing the bounding volume of the point's effect. When your fragment shader goes to render the surface of the volume, it looks up into the depth buffer for the scene already rendered, to figure out what point in the scene has already been rendered to that pixel of the render target. It then shades the fragment as though it was located at that position. In your case, that means calculating the distance from this projected scene point to the source point for the volume.


schematic diagram of deferred decal technique


The particulars will depend on the details of your use case (are your bounds cubes, spheres, cylinders? Can the camera get inside them? What type of shading effect needs to be applied within the bounds? Etc), but this type of technique is now pretty standard, so you should be able to find lots of references to get you started. Here's a sampling:




Why is XNA not considered a game engine?


I'm just wondering what XNA is missing, to be considered as a game engine. It does all the things a game engine should do (except the physics part); it also has support for every aspect defined in the Wikipedia article on game engines.


Why is XNA not considered a game engine?



Answer




Microsoft XNA is a set of tools with a managed runtime environment provided by Microsoft that facilitates computer game development and management. XNA attempts to free game developers from writing "repetitive boilerplate code" and to bring different aspects of game production into a single system.




It is designed as a framework - in fact, XNA is the Microsoft XNA Framework - so technically it's not an engine by name.


There is no 'engine' - if you notice, you derive your main class from XNA.Framework.Game and have to override the draw and update functions yourself. There is no central rendering system, or input system, or audio system ready out of the box. There is SpriteBatch and the vertex classes, there is KeyboardState, and there are some audio classes..but they are only abstractions over the low level drawing code.


EDIT: For the sake of usefulness, why does something matter if it's labelled as an engine, framework, library, or toolset?


To clear things up somewhat: I am developing an engine in XNA. Obviously I can't do that in something like Unreal, like Jonathan has mentioned. However, there are a few things I feel are important that XNA just doesn't have:


Plug-n-play: I want to be able to make some kind of template - have this HP, this mesh, this animation and BOOM! I have an NPC in my game.


Hidden low level - XNA does this already, but I don't want to fiddle around with GameServiceProviders. I just want to shove stuff together.


Game separated from engine - There may be a 'game' class, but I want to separate my logic and my code from the base system. I don't want if(player.hasitem(Item.SECRET_SWORD_OF_SECRETNESS) mixed with updating the buffers on my graphics renderer.


Wednesday, September 26, 2018

Tile coordinates


Simple question I have here.


Say my tile map is based on 32x32 tiles for an 800x600 image so let's say 25 tiles across and 19 down.


So now I have that cell 0 of any row contains the first 0-31 pixels, cell 1 contains then 32nd-63rd pixels, cell 2 has 64-96 pixels and so on. If I have my player somewhere and now I want to get the corresponding tile, what can I do? I can't just divide by 32 as this doesn't always work such as here:


Let's say I am testing both 64 and 96 in the x direction and am testing against the range of 64-96 (which should be in cell 2 of any row)


64/32 = 2 (this is the correct column for my tile map for any row) 96/32 = 3 (incorrect, the 96th pixel is still within column 2 for any row of the tile map)




Answer



Actually it seems that your calculation is correct - you are just mistaken about pixel 96. Column 3 contains pixels 64-95 inclusive, not 64-96. Dividing by the tile size is in fact the correct method.


What are some good learning resources for OpenGL?




I have been using the OpenGL ES on the iPhone for a while now and basically I feel pretty lost outside to the small set of commands I've seen in examples and adopted as my own. I would love to use OpenGL on other platforms and have a good understanding of it.


Every time I search for a book I find this HUGE bibles that seem uninteresting and very hard for a beginner. If I had a couple of weekends to spend on learning OpenGL what would be the best way to spend my time (and money)?




Answer



Be careful when you look at OpenGL tutorials, because many of them (NeHe) included just teach you things that you shouldn't do anymore. Todays OpenGL is a different beast that it was 10 years ago.


Some nice examples avoiding the deprecated stuff can be found here: http://www.g-truc.net/post-tech-content-sample.html



The OpenGL Samples Pack 4.0.1.0 is an update that brings the number of samples to a total of 58 samples; including 13 OpenGL 4 samples, 33 OpenGL 3.3 samples and 12 OpenGL 2 samples for Visual Studio 2008 and 2010 in 32 and 64 bits.



mathematics - matrix to rotate a vector to a known arbitrary axis


Let's say I have a vector V (v.x,v.y,v.z) which is normalized and points somewhere in 3d space. And that I have another vector Z of (0,0,1). Knowing only these two things I'm looking for a transformation matrix that will take the vector Z and turn it in to V.


Or some other way to get to the vector V from the vector Z.


In my application for this I'll be taking other vectors that are in a Z axis space and putting them in (or rotating them to) the same space as the V vector. But a proof that it's working will be to take Z and make it V.


I know that if I had this matrix I could multiply the vec3 by the matrix and get the answer. But making this matrix from only that destination vector is what I'm not sure how to do.


Seems like it might be super simple and that I'm just not thinking of it correctly. Answer right in front of my face?




Discerning arguments of verbs, predicates?


I think I get that a verb may utilize arguments. Does a predicate announce something of an object (or subject)?


In,



"The lake froze solid".



The lake seems a noun phrase that solid may predicate on?





java - Implement Bubble Shooter arrow rotation using LibGDX?


I'm trying to implement an arrow at the bottom of the screen on an Android device. This arrow is placed in the center of the screen and is supposed to rotate by a given angle. The problem is that when using the SpriteBatch's draw function for a TextureRegion it rotates the whole image, so the y coordinate also moves up a bit.


I want the arrow to always be in the center of the screen with the x, y coordinates and not move up the y coordinate. I want the y coordinate to stick to the bottom of the screen, but I still need to rotate the arrow. So I don't know if this is possible in my approach to do this.



If you have an approach in LibGDX that is very different from mine. I still want to see it because I don't care how I get this to work, I just want to get it to work somehow.


This far I've found this Rotation - libGDX that helped me get the rotation a little better, but I need an arrow like in the game called Bubble Shooter. Image of Bubble Shooter Arrow


The arrow should be the radius inside of an invisible circle, I guess, is one way to see it. See images below.


Example: enter image description here


enter image description here enter image description here



Answer



You can set the origin when using SpriteBatch#draw function. You'll have to substract half of the width when setting the x coordinate too:


batch.draw(
yourTexture, // the texture or texture region
x - yourTextureWidth / 2, y, // x and y coordinates taking into account the origin (horizontal origin is the middle yourTextureWidth / 2, vertical origin is the bottom 0)

yourTextureWidth / 2, 0, // the origin (horizontal origin is the middle yourTextureWidth / 2, vertical origin is the bottom 0)
yourTextureWidth, yourTextureHeight, // width and height (keep them the same)
1, 1, // scale (unaffected)
rotation // rotation in degrees
);

According to your needs, you'll have to set x to be half the screen width and set y to 0.


Note: We have to substract or add the origin offset to the position because the draw method origin parameters only affect rotation and scale. Thus, the origin to position should be added manually by substracting or adding to the x and y coordinates.


Tuesday, September 25, 2018

tense - I'm rather confused about Verb form


How can i know when to use -ing or -ed or infinitive without to?



We will soon have your car "going". (Why use "going"?)


It's nice to have people "smile" at you in the street (why use "smile"?)





Answer



Concerning your sentence with smile, I'll quote from one PDF by Marcus Callies that quotes Biber and Huddleston&Pullum:



verbs taking the bare inf. come from just two semantic classes:
(according to Biber:)
• perception verbs (feel, hear (tell), see, watch);
• verbs of modality or causation (dare, have, help, let, make)
...
(according to Huddleston&Pullum:)

sensory perception verbs (feel, hear, notice, observe, overhear, see, watch) • have, let and make among the causatives
• a few are found either with or without to: ought, dare, know and find (typical of BrE), help



In your second sentence, have is a verb of causation: you do something that causes people to smile at you. You can use either smile or smiling, with have but not with make, for example.




Concerning the car going, I guess we can use go but the meaning will change to "we will launch your car" or "we will make your car go away".




You cannot use the -ed form in either of your sentences, it would be ungrammatical



We will soon have your car went. (WRONG)

It's nice to have people smiled at you in the street. (WRONG)



I'm not 100% sure why, but it's probably because smiled and went are finite verbs, and in some constructions you are only allowed to use non-finite verbs. It's probably a "catenative construction" in your case: one verb connects to another verb.




Reference:



  • "The spread of bare infinitival complements in Present-Day English", by Marcus Callies


word usage - Just = only a short time after that






  1. I had just arrived home last night when I remembered that I had left my keys in the office





  2. I had arrived home last night, and only a short time after that, I remembered that I had left my keys in the office





These two have the same meaning, right?




linking verbs - Are these uses of "cut (hair)" right? What are the differences in their meanings?


I told the stylist I wanted my hair cut short.


I told the stylist I wanted my hair to be cut short.


I told the stylist I wanted that my hair be cut short.




quotations - British Punctuation versus American Punctuation


I've learned that American English use double quotation marks and place periods inside quotation marks while British English use single quotation marks and place periods outside quotation marks.




American: He called this phenomenon "the memory of water."


British: He called this phenomenon 'the memory of water'.



But some media adopt another style similar to the following sentence. Is this style British or American English?



He called this phenomenon "the memory of water".



Another question about American punctuation: Which of the following is correct in American English?




Did he call this phenomenon "the memory of water?"


Did he call this phenomenon "the memory of water"?





Monday, September 24, 2018

pronouns - Poor 'him' or 'he'? Reason?


I checked many dictionaries and the examples of poor in the context of sympathy state 'thing', 'you' or a direct name (proper noun). I wonder what is the correct form of the pronoun there?




Poor him/he?



Ngram shows both in practice!


Reason?




grammaticality - “Are” vs. “is” after “parents and the family”


I was reading the news on Yahoo and found a mistake (as per my opinion). I need your valuable feedback to make sure if it was a mistake or I am wrong! It is a paragraph on Yahoo. Please check and let me know.


On Yahoo:




There has been a shift of power, control and decision making from the parents and elders of the family to the individuals themselves. That is not saying that parents and the family is not involved in the decision, but there is much more emphasis placed on what the individuals want, what they are looking for and who they will be compatible with.



As per my opinion:



There has been a shift of power, control and decision making from the parents and elders of the family to the individuals themselves. That is not saying that parents and the family are not involved in the decision, but there is much more emphasis placed on what the individuals want, what they are looking for and who they will be compatible with.



Thanks in advance.




word difference - 18 hours vs for 18 hours



1.Babies need to sleep 18 hours.


2.Babies need to sleep for 18 hours.



Are these sentences different in meaning? As my teacher says, we use "for" to describe "continuous action without a pause".




prepositions - "It had now been two weeks since he had left the house"



It had now been two weeks since he had left the house.



Is this use of since correct? Is the tense of the verb after it correct?




Joystick example problem for android 2D


I've searched all over the web for an answer to this, and there are simular topics but nothing works for me, and I have no Idea why. I just want to move my sprite using a joystick, since I'm useless at math when it comes to angles etc I used an example, Ill post the code here:


    public float initx = 50; //og 425;

public float inity = 300; //og 267;
public Point _touchingPoint = new Point(50, 300); //og(425, 267);
public Point _pointerPosition = new Point(100, 170);
private Boolean _dragging = false;
private MotionEvent lastEvent;

@Override
public boolean onTouchEvent(MotionEvent event) {

if (event == null && lastEvent == null) {

return _dragging;
} else if (event == null && lastEvent != null) {
event = lastEvent;
} else {
lastEvent = event;
}
// drag drop
if (event.getAction() == MotionEvent.ACTION_DOWN) {
_dragging = true;


} else if (event.getAction() == MotionEvent.ACTION_UP) {
_dragging = false;
}

if (_dragging) {
// get the pos
_touchingPoint.x = (int) event.getX();
_touchingPoint.y = (int) event.getY();

// bound to a box

if (_touchingPoint.x < 25) {
_touchingPoint.x = 25; //og 400
}
if (_touchingPoint.x > 75) {
_touchingPoint.x = 75; //og 450
}
if (_touchingPoint.y < 275) {
_touchingPoint.y = 275; //og 240
}
if (_touchingPoint.y > 325) {

_touchingPoint.y = 325; //og 290
}

// get the angle
double angle = Math.atan2(_touchingPoint.y - inity,
_touchingPoint.x - initx) / (Math.PI / 180);

// Move the beetle in proportion to how far
// the joystick is dragged from its center
_pointerPosition.y += Math.sin(angle * (Math.PI / 180))

* (_touchingPoint.x / 70);
_pointerPosition.x += Math.cos(angle * (Math.PI / 180))
* (_touchingPoint.x / 70);

// stop the sprite from goin thru
if (_pointerPosition.x + happy.getWidth() >= getWidth()) {
_pointerPosition.x = getWidth() - happy.getWidth();
}

if (_pointerPosition.x < 0) {

_pointerPosition.x = 0;
}

if (_pointerPosition.y + happy.getHeight() >= getHeight()) {
_pointerPosition.y = getHeight() - happy.getHeight();
}

if (_pointerPosition.y < 0) {
_pointerPosition.y = 0;
}

}
public void render(Canvas canvas) {
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(joystick.get_joystickBg(), initx-45, inity-45, null);
canvas.drawBitmap(happy, _pointerPosition.x, _pointerPosition.y, null);
canvas.drawBitmap(joystick.get_joystick(), _touchingPoint.x - 26,
_touchingPoint.y - 26, null);
}

public void update() {

this.onTouchEvent(null);
}

og= original position. as you can see Im trying to move the joystick, but when I do it stops working correctly, I mean it still works like a joystick but the sprite dosnt move accordingly, if I for example push the joystick down, the sprite moves up, and if I push it up it moves left.


can anyone PLEASE help me, I've been stuck here for sooo long and its really frustrating.



Answer



You use _touchingPoint.x twice in this code but never _touchingPoint.y


 _pointerPosition.y += Math.sin(angle * (Math.PI / 180))
* (_touchingPoint.x / 70);
_pointerPosition.x += Math.cos(angle * (Math.PI / 180))

* (_touchingPoint.x / 70);

I think the first instruction must be


_pointerPosition.y += Math.sin(angle * (Math.PI / 180))
* (_touchingPoint.y / 70);

client server - How should I automatically update my entire game's files?



How should I automatically update my player's game assets and executables? It is preferable for the update software to be free. Updates must be small in size and not waste cpu-time. Also it has to be easy to run a update server to create new versions or logistically.


My use case is for updating player game versions such as in massive online clients or running distributed game testing or even normal games.




xna - Why my game is running slowly if it was launched from a wpf application?


i have some issues why my GameEditor. I would start my XNA project from it, like a debug-client. It opens and all works fine, but it runs on 45 frames until I hide the wpf form. then the framerate goes up and remains there, even if I return the wpf form.


    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
var gameAppDomain = AppDomain.CreateDomain("Game");
gameAppDomain.ExecuteAssembly(@"..\..\..\WindowsGame1\WindowsGame1\bin\x86\Debug\WindowsGame1.exe");

}

the game is a just a new xna game without any rendering, except my framerate counter.


/// 
/// This is the main type for your game
///

public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;

private FrameRateCounter frameRateCounter;

public Game1()
{
this.graphics = new GraphicsDeviceManager(this);
this.Content.RootDirectory = "Content";
}

///
/// Allows the game to perform any initialization it needs to before starting to run.

/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
///

protected override void Initialize()
{
// TODO: Add your initialization logic here
this.frameRateCounter = new FrameRateCounter(this);
base.Initialize();
}


///
/// LoadContent will be called once per game and is the place to load
/// all of your content.
///

protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
this.frameRateCounter.LoadContent();

// TODO: use this.Content to load your game content here
}

///
/// UnloadContent will be called once per game and is the place to unload
/// all content.
///

protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here

}

///
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
///

/// Provides a snapshot of timing values.
protected override void Update(GameTime gameTime)
{
this.frameRateCounter.StartUpdateTimer();


// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();

// TODO: Add your update logic here

base.Update(gameTime);
this.frameRateCounter.EndUpdateTimer(gameTime);
}


///
/// This is called when the game should draw itself.
///

/// Provides a snapshot of timing values.
protected override void Draw(GameTime gameTime)
{
this.frameRateCounter.StartDrawTimer();
this.GraphicsDevice.Clear(Color.CornflowerBlue);


// TODO: Add your drawing code here

this.frameRateCounter.EndDrawTimer(gameTime);
base.Draw(gameTime);
}
}

If I do the same for a WinForms application, I dont have that issue. My first try was to launch it in an TASK/Thread but then it crashes after 15-20 min if I have loaded my soundeffects. The event log says it was "XAudio2_6.dll_unloaded" with a access violation exception.


hre is my test game: https://www.dropbox.com/s/gtt49lwquyoo86e/WindowsGame1.zip?dl=0




algorithm - Choose tile based on adjacent tiles


I am working on a tiled map editor, and I need to choose tiles automatically, based on the adjacent tiles. For example, when placing a road tile, next to another road tile, the two need to be oriented so that they form a continuous road. If there are other roads around them, we may need to use corner or intersection tiles.


Can anyone recommend some algorithms for doing this? The game uses an 8-directional square tiled map.



Answer



Maybe this is how it's typically done. You have your list of different tiles that represent a road tiles in all their possible orientations. Left to right, all four corners, top to bottom, whatever. Now you'll index all those tiles with a byte each. 8 bits, one for each direction. This could be in a hashmap or by file name... however you want to do this.


So you have this:


enter image description here



The byte code for the above tile is 00000000. Then your tile that goes from left to right (or right to left) is like this:


enter image description here


The byte code for that tile is 10001000, or 136. As another example, lets look at a three way intersection:


enter image description here


The byte code for that tile is 10101000.


You probably see where I'm going. You set bit positions in the byte representing connections. This is far better than trying to do some big if/else chain that I've seen before. When you're looking to place a tile, examine the tiles around it and create a byte along the way. Set 1's for tiles that have roads (or whatever you're looking to connect) and 0's for tiles that don't. When you're done, you'll have the byte code for the exact tile you need.


Note that when creating the assets you can reuse a lot of them by simply rotating and assigning the correct byte code to it.


EDIT: Updated images to be less crappy. Yes those are better than before.


iphone - Network client-server message exchange and clock synchronization help


i'm doing a fast paced physics game that is a table hockey. With two mallets and one puck. The game runs on iphone / ipad and i'm doing the multiplayer part through GameCenter.


This is how the network system works. The client wich stars the match, will be settled as the server and the one that accepts the match request is the client.



The 'server' has the physics running and the response is immediate and the client also has their physics running so it looks smooth between messages exchange. What i do as the server, is that i send to the client my puck velocity and my position and the client adjusts his puck velocity/position related to the server to keep it sync. Otherwise the physics desynchronizes and it screws it up.


When the network latency is good, bellow 100ms the results are pretty good, i got a smooth playable game on the client side and the weird behavior are minimum. The problem happens when the lag is around 150 to 200ms. In that case, happens that my client puck already hitted a edge and inverted direction but it receives a delay message from the server and it backs a bit causing a weird feeling to the ball behavior.


I've readed a few things about it:


Pong Network Example


Click Synchronization Example


Wikipedia on Clock Sync


So, how can i solve this? As far as i've read the best option that i have is to do a clock synchronization on the server/client with a timestamp so that when i get delay messages related to my clock, i just ignore then and let the clients simulation do the job. Do you guys agree with that? And since im sending data unreliable (UDP) i may get delayed messages or messages out of order.


If that is the best approach, how do i implement the clock synchronization. I've read the steps on how to but i didn't quite understand it.


It says that:




  1. Client stamps current local time on a "time request" packet and sends to server.

  2. Upon receipt by server, server stamps server-time and returns

  3. Upon receipt by client, client subtracts current time from sent time and divides by two to compute latency. It subtracts current time from server time to determine client-server time delta and adds in the half-latency to get the correct clock delta. (So far this algothim is very similar to SNTP)

  4. The client repeats steps 1 through 3 five or more times, pausing a few seconds each time. Other traffic may be allowed in the interim, but should be minimized for best results The results of the packet receipts are accumulated and sorted in lowest-latency to highest-latency order. The median latency is determined by picking the mid-point sample from this ordered list.

  5. All samples above approximately 1 standard-deviation from the median are discarded and the remaining samples are averaged using an arithmetic mean.


Following this example i would have this:


Lets pretend the game has loaded and my client time is 0 now, so i send to the server that my time is 0.


The messages takes 150ms to get to the server but the server's clock had already started and is 1 second ahead of the client. When the server get the message the time will be: 1.15 and sends that time to client, are we good? Lets pretend our lag is constant at 150ms.


Now the client receives the time 1.15 and subtracts current time from sent time and divides by two to compute latency. Wich is: 0.3 - 0 = 0.3/2 -> 150ms.



It subtracts current time from server time to determine client-server time delta and adds in the half-latency to get the correct clock delta:
Client time: 0.3 Server time 1.15
0.3 - 1.15 = .85 + latency(.15) = 1


How is that synchronized? What am i missing?


It's my first time on multiplayer and network experience, so i'm a bit confused.


Thank you.



Answer



The algorithm posted was correct, but in your example you are forgetting about the time it takes for the server packet to get to the client, so:


Server time: 1
Client time: 0

Client sends 0 to server

... 150ms to get to server (ping is 300! not 150ms in this case. Ping is round-trip)

Server time: 1.15
Client time: 0.15
Server receives packet and sends client 1.15

... 150ms to get back to client


Server time: 1.30
Client time: 0.30
Client receives 1.15 from server

Now as you can see, if the client changed its clock to 1.15, it would be 0.15 behind the server, this is why you have to adjust for the Ping (aka Round Trip Time [RTT]). Here is the full delta time calculation done over many steps:


Server Time - Current Time + Ping / 2
= Server Time - Current Time + (Current Time - First Packet Time) / 2
= 1.15 (Perceived, not actual!) - 0.30 + (0.30 - 0.00) / 2
= 1.00


This gives us the correct delta time of 1.00 seconds


python - Collision Resolution of Axis-Aligned Bounding Boxes that Change Size


I am developing an action platformer in Python, with Pygame. That said, my question is a general one about collision resolution strategies.



I use an axis-aligned bounding box for the purposes of collision detection. The bounding box changes sizes depending on the sprite's action and the frame of the action's animation.


When I update my sprite's position, I first update the y-coordinate, check for and resolve collision in the y-direction, then do the same for the x-coordinate. When I resolve collision, I simply move the bounding rect's sides to align flush with the appropriate walls.


Because the bounding rect changes sizes throughout my animations, I am noticing buggy behavior in certain situations when the frame moves from a smaller one to a larger one. The change of frame results in the sprite intersecting a wall and his position is resolved such that he falls off the map.


Here is a diagram illustrating the problem:


enter image description here


It doesn't matter whether I resolve in the x-direction or the y-direction first. They result in reciprocal buggy behavior when the next frame is wider or taller, respectively.


My question concerns general collision resolution strategies for axis-aligned bounding boxes that change size and shape. What are the best algorithms for collision resolution that avoid this issue?


Here are some of the functions and values I have access to:



  • colliderect -- tests if two rectangles collide


  • collidepoint -- boolean that tests if a point collides with a rectangle

  • rect.topleft, rect.topright, rect.bottomleft, rect.bottomright, rect.center, rect.centerx, rect.centery -- various points on the rectangles

  • rect.left, rect.right, rect.top, rect.bottom -- values for the sides of the rects

  • various vectors

  • in short, the usual stuff


Apologies if this question is a dupe. I imagine it is a pretty common one, though I couldn't find anything that helped me specifically.



Answer



In brief there are two ways of doing this. Both are relatively fast and simple to run.


Method 1

If the AABB (axis aligned bounding box) changes every frame because of animations, then you can simply wait until after the sprite has been moved and the next frame of the animation has played before resolving the collisions


def MainLoop():
#Update the position
rect.center = rect.center + velocity

#I don't know how you are doing your animations, but play the next frame here
Animate.PlayNextFrame()

#Now you want to check for collisions as normal now that everything has moved in the frame we can check for collisions once
CheckCollisions()


This means that the collision detection occurs only once animation and the movement has occurred. This prevents the need to do collision detection more than once per frame and takes the animation into account.


Method 2
Make a dummy aabb for collision detection that follows the main character which has a fixed size. This will occasionally result in some minor intersection between the character and the wall but in most cases it looks fine.
Sprite intersection isn't a big deal
This is also relatively easy to implement and very fast to run.


Sunday, September 23, 2018

unity - Cube changes position when I use a script to change its UV mapping


I try to code a Minecraft like game with Unity 2017.3. I found a C# script for creating a UV mapped cube with the following layout, using my own texture with 64x64 pixel sides:


MY UV map


If I run the game my cube is now placed in the air. How do I control its position?


MY cube is not on the ground


Here is the script I'm using:


using UnityEngine;
using System.Collections;


[RequireComponent(typeof (MeshFilter))]
[RequireComponent(typeof (MeshRenderer))]
public class UVMapping : MonoBehaviour {

void Start () {

float size = 1f;

Vector3[] vertices = {

new Vector3(0, size, 0),
new Vector3(0, 0, 0),
new Vector3(size, size, 0),
new Vector3(size, 0, 0),
new Vector3(0, 0, size),
new Vector3(size, 0, size),
new Vector3(0, size, size),
new Vector3(size, size, size),
new Vector3(0, size, 0),
new Vector3(size, size, 0),

new Vector3(0, size, 0),
new Vector3(0, size, size),
new Vector3(size, size, 0),
new Vector3(size, size, size),
};

int[] triangles = {
0, 2, 1, // front
1, 2, 3,
4, 5, 6, // back

5, 7, 6,
6, 7, 8, //top
7, 9 ,8,
1, 3, 4, //bottom
3, 5, 4,
1, 11,10,// left
1, 4, 11,
3, 12, 5,//right
5, 12, 13
};


Vector2[] uvs = {
new Vector2(0, 0.66f),
new Vector2(0.25f, 0.66f),
new Vector2(0, 0.33f),
new Vector2(0.25f, 0.33f),
new Vector2(0.5f, 0.66f),
new Vector2(0.5f, 0.33f),
new Vector2(0.75f, 0.66f),
new Vector2(0.75f, 0.33f),

new Vector2(1, 0.66f),
new Vector2(1, 0.33f),
new Vector2(0.25f, 1),
new Vector2(0.5f, 1),
new Vector2(0.25f, 0),
new Vector2(0.5f, 0),
};

Mesh mesh = GetComponent ().mesh;
mesh.Clear ();

mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.Optimize (); // this is deprecated
mesh.RecalculateNormals ();
}
}

Answer



The default Unity cube mesh has its center at the object's pivot ((0, 0, 0) in local space), and extends to -0.5 and +0.5 on each axis.


The script you're using creates a new cube-shaped mesh with one corner at the pivot, extending from 0 to size on each axis.



So if you're using it to replace a default Unity cube at runtime, you'll find it's shifted by 0.5 units.


You can fix this by adding a quick fixup after your vertices block:


for(int i = 0; i < vertices.Length; i++)
vertices[i] -= Vector3.one * 0.5f * size;

Or you can go through each line and replace every size by 0.5f * size,
and every 0 by -0.5f * size (defining an extents = 0.5f * size makes this neater)


One last note: each cube you use this script on will create its own copy of the mesh, eating memory and draw calls unnecessarily. You might want to consider grouping these, so that you calculate the mesh only once and share it among many cubes. Or even better, just make the mesh you want offline and import it as an asset that all your cubes can reference.


unity - How can I debug a black screen when testing on a device?


I have made an Android game with Unity. But, when I opened my game, I see a black screen and a closed game.



It works on a tablet but does not work on mobile phones. I tested it on 2 mobile phones.


On the first phone I installed it on, I see nothing but a black screen and closed game.


On the second one, it installed once and worked, but when I uninstalled it and tried to install it again, I get the black screen and closed game.


What can I do to help me find out what is going on?




java - OpenGL Camera causes spatial distortion


I'm trying to implement a 3D camera of the "Orbit around the origin" variety in a game engine I'm developing in order to learn about 3D graphics and game programming. I have a basic handle on the required math, and have implemented my own crude 3D math library and matrix stack (functionally similar to the one in OpenGL's compatibility profile). My first attempts at a camera failed miserably, until I decided that I should use quaternions to represent rotation. Once I'd done that, I had a camera that moved in the direction I expected it to at about the right speed and fairly smoothly, but there is an odd spatial distortion effect that I can't seem to get rid of. I have posted a brief video on YouTube showing exactly what is happening.



I honestly don't know what could be causing this issue, the magnitude of the distortion appears to reach a maximum at certain angles, but beyond that I'm not sure what I should be looking at. Right now my chief suspect is my quaternion math code, because the matrix stack appears to be behaving itself and if something was wrong with my matrix math code I would be having more serious issues than this.


I'm not sure what information or code I can provide that would be of any use, so I'll start with the code that handles quaternion math.


public class Quaternion {
private float w;
private float x;
private float y;
private float z;

public Quaternion(){
this(1.0f,0.0f,0.0f,0.0f);

}

public Quaternion(float W, float X, float Y, float Z){
w = W;
x = X;
y = Y;
z = Z;
}

public void loadIdentity(){

w = 1.0f;
x = 0.0f;
y = 0.0f;
z = 0.0f;
}

public float magnitude(){
//AKA the "norm"
return (float) Math.sqrt(w*w + x*x + y*y + z*z);
}


public void qNormalize(){
float mag = this.magnitude();
w /= mag;
x /= mag;
y /= mag;
z /= mag;
}

public void qMultiply(Quaternion q){

this.qMultiply(q.w, q.x, q.y, q.z);
}

private void qMultiply(float w2, float x2, float y2, float z2){
//Performs A*B, where this Quaternion is A
this.w = w*w2 - x*x2 - y*y2 - z*z2;
this.x = w*x2 + x*w2 + y*z2 - z*y2;
this.y = w*y2 + y*w2 + z*x2 - x*z2;
this.z = w*z2 + z*w2 + x*y2 - y*x2;
}


public float[] qMatrix(){
//Return a 4x4 matrix representation of this Quaternion, column-major like OpenGL prefers
float w2 = w*w;
float x2 = x*x;
float y2 = y*y;
float z2 = z*z;

if(Math.abs(w2+x2+y2+z2 - 1.0) >= 0.000001){
this.qNormalize();

return this.qMatrix();
}

return new float[]{
1.0f - 2.0f*y2 -2.0f*z2, 2.0f*x*y + 2.0f*w*z, 2.0f*x*z - 2.0f*w*y, 0.0f,
2.0f*x*y - 2.0f*w*z, 1.0f - 2.0f*x2 - 2.0f*z2, 2.0f*y*z + 2.0f*w*x,0.0f,
2.0f*x*z - 2.0f*w*y, 2.0f*y*z + 2.0f*w*x, 1.0f - 2.0f*x2 - 2.0f*y2,0.0f,
0.0f,0.0f,0.0f,1.0f
};
}


public void qFromAA(float angle, float[] axis){
//create a Quaternion from an axis-angle representation

if(Vector.magnitude(axis) == 0.0f){
this.loadIdentity();
return;
}

float theta = angle/2.0f;

axis = Vector.scale((float)Math.sin(theta), Vector.normalize(axis));

w = (float)Math.cos(theta);
x = axis[0];
y = axis[1];
z = axis[2];
}

public String toString(){
return "w: "+w+"\tx: "+x+"\ty: "+y+"\tz: "+z+"\tmag: "+(x*x+y*y+z*z+w*w);

}

}

Any ideas about where I should start?



Answer



Are you sure your code for quaternion multiplication and your code for quaternion matrix converion is correct?


I had a typo in one of my formulas once that cost me nearly half a day.


btw... http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/index.htm is a great reference for quaternion math.


software engineering - Is storing all game objects in a single list an acceptable design?


For every game I've made, I just end up placing all my game objects (bullets, cars, players) in a single array list, which I loop through to draw and update. The update code for each entity is stored within it's class.


I've been wondering, is this the right way to go about things, or is a faster more efficient way?



Answer



There is no one right way. What you're describing works, and is presumably fast enough that it doesn't matter since you seem to be asking because you're concerned about the design and not because it's caused you performance issues. So it is a right way, sure.


You could certainly do it differently, by for example keeping a homogenous list for each object type or by ensuring everything in your heterogenous list is grouped together such that you have improved coherency for the code that is in-cache or to allow parallel updates. Whether you'd see any appreciable performance improvement by doing this is difficult to say without knowing the scope and scale of your games.


You could also further factor out the responsibilities of your entities -- it sounds like entities both update and render themselves at the moment -- to better follow the Single Responsibility Principle. This can increase the maintainability and flexibility of your individual interfaces by decoupling them from one another. But again, whether or you'd see a benefit from the extra work that would entail is hard for me to say knowing what I know of your games (which is basically nothing).



I would recommend not stressing too much about it, and keep in the back of your head that it might be a potential area for improvement if you ever notice performance or maintainability issues.


c++ - How to create and populate a 2D Texture Arrays in DirectX11


I have generated a bunch of ID3D11ShaderResourceView that are a 2D textures that have a depth map screen shot for my lights shadows. I would like to take all of these textures and put them into a single 2D Texture Array.



I have seen examples of how to create a 2D Texture array like in this question here but I don't know how to copy the data to the newly created texture array.



Answer



You can use CopySubresourceRegion to copy data between textures. "Subresource" means a combination of mip level and array index, so here you would copy to the subresource corresponding to the desired index in your texture array.


However, it's best to avoid copying data between textures if possible, as it does take time. Instead of rendering to a bunch of 2D textures and copying into the array, it would be faster to render directly to the array. You can do this by creating a render target view that points to a specific subresource in the texture array.


Saturday, September 22, 2018

mathematics - How would I translate screen coordinates to Isometric coordinates?


I have a function isoToScreen(x, y) that converts Isometric coordinates to Screen coordinates.



var tileW = 16;
var tileH = 16;

var isoToScreen = function(x, y) {
var posX = (x - y) * tileW;
var posY = (x + y) * tileH / 2;

return [posX, posY];
};


But how would I make a function that converts screen coordinates back to Isometric coordinates?


var pos = screenToIso(16, 8); 
pos[0] = 1; // Iso X
pos[1] = 0; // Iso Y

Answer



var screenToIso = function(screenX, screenY)
{
var isoX = screenY / tileH + screenX / (2*tileW)
var isoY = screenY / tileH - screenX / (2*tileW)


return [isoX, isoY];
}

To get this function you need to rewrite the original math


screenX = (isoX - isoY) * tileW
screenY = (isoX + isoY) * tileH / 2

Starting with the first line you get the following:


screenX = (isoX - isoY) * tileW
screenX / tileW = isoX - isoY

screenX / tileW + isoY = isoX

The second line:


screenY = (isoX + isoY) * tileH / 2
2*screenY = (isoX + isoY) * tileH
2*screenY / tileH = isoX + isoY
2*screenY / tileH - isoX = isoY

Now the two lines look as follows:


A) isoX = screenX / tileW + isoY

B) isoY = 2*screenY / tileH - isoX

Then substitute isoY in the line A, with the formula derived from line B:


isoX = screenX / tileW + 2*screenY/tileH - isoX
isoX+isoX = screenX / tileW + 2*screenY/tileH
2*isoX = screenX / tileW + 2*screenY/tileH
isoX = screenX / (2*tileW) + screenY/tileH
isoX = screenY/tileH + screenX / (2*tileW)

And finally, substitute isoX in line B, with the formula derived from line A:



isoY = 2*screenY / tileH - screenX / tileW - isoY
2*isoY = 2*screenY / tileH - screenX / tileW
isoY = screenY / tileH - screenX / (2*tileW)

Solving linear equations comes very much in handy for a lot of programming, especially graphics or game related programming. Pick up a book on Algebra or read some online tutorials, you will thank yourself later.


difference - "as we discuss in detail in a moment" - why not "as we'll discuss"?




The term 'raising verb' is potentially confusing. It is not the verb itself that undergoes movement. Rather, it is the complement subject that raises into the matrix clause, as we discuss in detail in a moment. (a webpage)



I understand that the authors use the Present Simple in a way similar to its use in description of scheduled events:



I fly into Bombay at noon, and then speak at the conference at 3:00 p.m.



But since it's due to happen "in a moment", it's unlikely to have been scheduled, so wouldn't it be better to say "we'll discuss"?


Is there any difference in tone between "we discuss" and "we'll discuss" and which construction is preferable in this context (textbook narrative)?



Answer



It depends on how the writer wants you to perceive the web page.



If they want you to think of it as a completed document, which you are coming along and reading now that it's done, then the present is appropriate. "My explanation already exists. You haven't gotten to it yet, but it's there."


If they want you to think of it as them talking to you, then the future - "we'll discuss" - would be more appropriate.


Both are correct; they just evoke different tones.


Friday, September 21, 2018

unity - I'm still not sure how to control each door individual?


What I want to do is something more or less very simple. The main bool flag lockDoors control all the doors and this is working fine now. But now I want to add a flag to each individual door so I can change the door lock state for each specific door. And if I change the lockDoors state it will change all the doors except if I changed some individuals.


I tried to add a new class name DoorControl and made it also Serializable but not sure if this is the way and how to do it.


Example of how it should look like in the Inspector:


lockDoors checkbox here (This is the flag for all the doors) and then:


Door1
checkbox here
Door2
checkbox here
Door3
checkbox here

So I can keep controlling the whole doors or each door individual.


using System.Collections;
using System.Collections.Generic;

using System.Linq;
using UnityEngine;

public class DoorsLockManager : MonoBehaviour
{
[System.Serializable]
public class DoorControl
{
public bool doorLock;
}


public bool lockDoors = false;
public List _doors = new List();
public DoorControl[] doorscontrol;

private bool[] doorsLocks;
private Renderer rend;
private Shader unlitcolor;
private List DoorShieldFXLocked = new List();



private void Start()
{
DoorShieldFXLocked = GameObject.FindGameObjectsWithTag("DoorShield").ToList();
unlitcolor = Shader.Find("Unlit/ShieldFX");

var doors = GameObject.FindGameObjectsWithTag("Door");
foreach (var door in doors)
{
_doors.Add(door.GetComponent());

}

doorscontrol = new DoorControl[_doors.Count];

ChangeDoorsLockStates();
}

private void Update()
{
ChangeDoorsLockStates();

}

private void ChangeDoorsLockStates()
{
for (int i = 0; i < DoorShieldFXLocked.Count; i++)
{
if (lockDoors == true)
{
ChangeColors(Color.red, Color.green, i);
}

else
{
ChangeColors(Color.red, Color.green, i);
}
}

for (int x = 0; x < _doors.Count; x++)
{
if (lockDoors == true)
{

LockDoor(x);
}
else
{
UnlockDoor(x);
}
}
}

private void ChangeColors(Color32 lockedColor, Color32 unlockedColor, int index)

{
var renderer = DoorShieldFXLocked[index].GetComponent();
renderer.material.shader = Shader.Find("Unlit/ShieldFX");

if (lockDoors == true)
{
renderer.material.SetColor("_MainColor", lockedColor);
}
else
{

renderer.material.SetColor("_MainColor", unlockedColor);
}
}

public void LockDoor(int doorIndex)
{
_doors[doorIndex].ChangeLockState(true);
}
public void UnlockDoor(int doorIndex)
{

_doors[doorIndex].ChangeLockState(false);
}
}

And this script is attached to each door:


using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class HoriDoorManager : MonoBehaviour

{
private List doors = new List();
private bool doorLockState;

private void Start()
{
if (transform.parent != null)
{
Transform parent = transform.parent;
var children = parent.GetComponentsInChildren();


if(children != null)
{
foreach (Transform door in children)
{
if (door.name == "Door_Left" || door.name == "Door_Right")
doors.Add(door.GetComponent());
}
}
}

}

void OnTriggerEnter()
{
if (doorLockState == false)
{
if (doors != null)
{
for(int i =0; i < doors.Count; i++)
{

doors[i].OpenDoor();
}
}
}
}

public void ChangeLockState(bool lockState)
{
doorLockState = lockState;
}

}

Answer



Okay I just did a mockup of what I think it is you want:


//each door has a DoorControl object which holds the bool variables and handles 
//changing the variables
[System.Serializable]
public class DoorControl
{
public bool doorLock;
public bool doorLockOverride;


public DoorControl(bool doorLock = true, bool doorLockOverride = false)
{
this.doorLock = doorLock;
this.doorLockOverride = doorLockOverride;
}

public void SetDoorLockState(bool val)
{
doorLock = val;

}
}


public class Door : MonoBehaviour
{
public DoorControl thisDoorControl;

private void Start()
{

thisDoorControl = new DoorControl();
}

private void Update()
{
if (thisDoorControl.doorLockOverride)
{
OpenDoor();
return;
}

if (thisDoorControl.doorLock)
{
OpenDoor();
}
else
{
CloseDoor();
}
}


private void OpenDoor()
{
//open your door
}

private void CloseDoor()
{
//close your door
}
}


You could then reference each doors DoorControl in your manager class and stuff it into a List or an DoorControl[] array like this:


public class DoorManager : MonoBehaviour
{
public List doors = new List();
public List doorControls = new List();

//this is just to initialize the list with values from all the doors. You could
//assign those directly in the inspector
private void Start()

{
foreach(var door in doors)
{
doorControls.Add(door.thisDoorControl);
}
}

public void ChangeAllLockOverrides(bool val)
{
foreach(var door in doorControls)

{
door.doorLockOverride = val;
}
}
}

The manager then looks like this in the inspector: Unity screenshot


Keep in mind that this will open/close the door every frame because I call it in Update. This is no good solution and you should not copy paste this if you plan to keep your performance as high as possible. I hope this points you in the right direction.


adjectives - "Despicable Me": can "me" be used in such a way?



We know a movie named Despicable Me. I guess it means "I am despicable". But can me be used in such a way?


For example, can I further say unavoidable me to mean "I am unavoidable"? Are there other examples? Or can I just do this with any adjective?



Answer



Considering this issue strictly in terms of grammar, there are two things to consider here.


First, in the phrase "despicable me", "me" is a noun (a pronoun, actually, but still a noun) and "despicable" is an adjective. So in one sense, yes, it is perfectly grammatically appropriate to place adjectives before nouns ("red firetruck") and by extension it works to place "despicable" before "me".


Second, the sentence as a whole is a fragment. There is no noun performing a verb; there is simply a lone adjective-noun pair, which technically is not enough to form a full, proper English sentence. However, it could be considered an exclamatory sentence, especially in context, so we let it slide.


In short, it is a proper adjective-noun phrase, and we'll look the other way on the whole fragment thing, so yes, it can be used in such a way.


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