Friday, June 30, 2017

grammatical number - "Everyone has their own stories" vs "Everyone has their own story" - which one is correct?


Which of them is correct?




Everyone has their own stories



or



Everyone has their own story



What I'm asking about is that how could we decide that we should use a plural or singular noun after the word "own"? Is it correct to think that if a subject of the sentence is singular then a noun following the word "own" must be singular too?


Here are some examples below:



People have their own stories.



Dang has his own story.


Evenyone has their own story.





word choice - How to choose between shall and should?




  1. Where shall we go?


  2. Where should we go?





  3. Shall we eat outside?



  4. Should we eat outside?


Which is correct and why? Thank you in advance.




word usage - Can "the elderly" be used for some specific old people?


I wonder if I can use "the elderly", by which I mean old people, to refer to a specific group of old people. For example:



The elderly with death anxiety



Is this acceptable? Or should I use something like old people with death anxiety instead?





Thursday, June 29, 2017

c++ - Camera rotation - First Person Camera using GLM



I've just switched from deprecated opengl functions to using shaders and GLM math library and i'm having a few problems setting up my camera rotations (first person camera). I'll show what i've got setup so far.


I'm setting up my ViewMatrix using the glm::lookAt function which takes an eye position, target and up vector


// arbitrary pos and target values
pos = glm::vec3(0.0f, 0.0f, 10.0f);
target = glm::vec3(0.0f, 0.0f, 0.0f);
up = glm::vec3(0.0f, 1.0f, 0.0f);

m_view = glm::lookAt(pos, target, up);

i'm using glm::perspective for my projection and the model matrix is just identity



m_projection = glm::perspective(m_fov, m_aspectRatio, m_near, m_far);

model = glm::mat4(1.0);

I send the MVP matrix to my shader to multiply the vertex position


glm::mat4 MVP = camera->getProjection() * camera->getView() * model;
// in shader
gl_Position = MVP * vec4(vertexPos, 1.0);

My camera class has standard rotate and translate functions which call glm::rotate and glm::translate respectively



void camera::rotate(float amount, glm::vec3 axis)
{
m_view = glm::rotate(m_view, amount, axis);
}
void camera::translate(glm::vec3 dir)
{
m_view = glm::translate(m_view, dir);
}

and i usually just use the mouse delta position as the amount for rotation



Now normally in my previous opengl applications i'd just setup the yaw and pitch angles and have a sin and cos to change the direction vector using (gluLookAt) but i'd like to be able to do this using GLM and matrices.


So at the moment i have my camera set 10 units away from the origin facing that direction. I can see my geometry fine, it renders perfectly. When i use my rotation function...


camera->rotate(mouseDeltaX, glm::vec3(0, 1, 0));

What i want is for me to look to the right and left (like i would with manipulating the lookAt vector with gluLookAt) but what's happening is It just rotates the model i'm looking at around the origin, like im just doing a full circle around it. Because i've translated my view matrix, shouldn't i need to translate it to the centre, do the rotation then translate back away for it to be rotating around the origin? Also, i've tried using the rotate function around the x axis to get pitch working, but as soon as i rotate the model about 90 degrees, it starts to roll instead of pitch (gimbal lock?).


Thanks for your help guys,


and if i've not explained it well, basically i'm trying to get a first person camera working with matrix multiplication and rotating my view matrix is just rotating the model around the origin.



Answer



Answer:


Thanks for your help guys.



I just kept track and updated the position and heading variable separately from the view matrix.


glm::vec3 m_position;
glm::vec3 m_direction;

...

// speed is usually 0.1f or something small like that
void camera::rotate(float amount, glm::vec3& axis)
{
m_direction = glm::rotate(m_direction, amount * m_speed, axis);

}

void camera::translate(glm::vec3& direction)
{
m_position += direction;
}

// call this once per loop
// m_up is glm::vec3(0, 1, 0) for a first person camera
void camera::update()

{
m_view = glm::lookAt(m_position, m_position + m_direction, m_up);
}

and just if anyone is curious about strafing of the camera i'll add that code in


enum MovementType {FORWARD, BACKWARD, STRAFE_L, STRAFE_R};

void camera::applyMovement(MovementType movement)
{
switch (movement)

{
case FORWARD:
m_position += m_direction;
break;
case BACKWARD:
m_position -= m_direction;
break;
case STRAFE_LEFT:
m_position += glm::cross(m_direction, m_up);
break;

case STRAFE_RIGHT:
m_position -= glm::cross(m_direction, m_up);
break;
}
}

libgdx - How to match font size with screen resolution?


So I'm working on a game using LibGDX, and I have a problem.



To make my game fit most resolutions, I created a base asset for each aspect ratio, for example, a main menu background image, I made it in 800X600 for 4:3, 1280X720 for 16:9 etc.


Now I am trying to incorporate TextButtons into the game, for the options; My problem is that I can't figure out which font sizes match with which screen resolutions. Is there a way to figure this out, or do I have to go one by one through each of the resolutions I have and just manually match the text to the resolution?



Answer



It's easy: Fonts do not need to match resolution, they need to match pixel density.


Pixel density is measured as pixels per inch(PPI), or pixels per centimeter. There's also a measure unit called density independent pixels(DP). It is defined that 1dp is the size one pixel has on a 160 PPI screen.


Now coming back to fonts, try to make this test: put your laptop to run on 720p. Take a look on the size of the font. Now plug it into the 1080p 42" monitor of your desktop. If your monitor outputs the right information about its size, then the font should have EXACTLY the same size it had on the 720p screen. Imagine how weird it would be if text in your laptop had a different size than the text on your desktop monitor. With that said, larger resolutions should give more detail to the font, larger screens should give more content to be shown.


The same fact can be observed on text editors. A 72pt font should look on the screen the same it would when printed on paper.


All this means you probably should want the same size across all display sizes (with some exceptions). If you want to base yourself somewhere, websites usually use 12pt fonts, MS Windows uses 11pt and 12pt fonts.


This chart (also included in the bottom of the answer) tell us 12pt in CSS is roughly equal to 16px also in CSS (As if this wasn't confusing enough, a px in CSS is the same as dp everywhere else), so let's say you'll make your fonts 16dp on LibGDX.


On your game, use the FreeTypeFontGenerator to generate fonts dynamically, this way you can consider the screen density when creating them:



BitmapFont createFont(FreeTypeFontGenerator ftfg, float dp)
{
return ftfg.generateFont((int)(dp * Gdx.graphics.getDensity()));
}
//On Init
BitmapFont buttonFont = createFont(arial, 16); //16dp == 12pt

This works because Gdx.graphics.getDensity() is equal to YourScreenDensity/160 thus, is a "scale factor" to bring things to the size they would be on a 160ppi screen.


About the exceptions I mentioned earlier: you'll probably want fonts re-sizing accordingly to screen size in case of logos, promos, etc. But keep in mind that you'll be better off making these on a graphics editor like Photoshop or Gimp, anyway.


The other exception is text on tiny screens. 4.5" or smaller phone screens, wearables. Usually you won't have time to make scrolling content, or you just won't be able to afford putting so much content on that screen. You may try to scale the font 1dp down, as the reader will probably have the phone very close to their face, they probably won't have a problem reading. Keep in mind you may annoy the player reading unreadable small text.



TL;DR:



  • Physical size roughly won't change directly with screen size or resolution, but with a combination of both (screenSize/resolution the famous PPI)

  • Think of pt and dp. Forget about screen pixels until you have to draw the final result.

  • Create your font at runtime with a reasonable size.

  • Converting dp to screen pixels: pixels = dp * Gdx.graphics.getDensity();

  • If you are using a engine which does no give you converter to dp like LibGDX's Gdx.graphics.getDensity(), you can try: densityFactor = Screen.getPixelsPerInch() / 160.0f, then pixels = dp * densityFactor


EDIT:


2014, Jun 25 on Google IO, Matias announced a new style guidelines for Android, it includes a new Roboto font and typography guidelines. Take this table as a guide:



Android font size guidelines, taken fron google.com/design


EDIT2:


Included CSS font size chart in case the link goes rot: CSS font sizes


java - What can be the cause of sudden lag spikes in my Android game?


My Android game has sudden lag spikes sometimes. I know this is due to something going wrong. My phone has a 1GHz processor so there shouldn't be a problem. Basically I use the Canvas class to render my entire game (I am about to learn OpenGL and don't know if this is the cause). I have a main game loop and about 4 threads. Why does it lag?


Thanks in advance.




Answer



This is most presumably the garbage collector kicking in.


There is no clean way to solve this problem unless you are willing to ditch Java for another language such as C++. See How can I avoid garbage collection delays in Java games? (Best Practices) for a few hints on how to mitigate the problem.


Wednesday, June 28, 2017

How do you come up with ideas for new games?




What is the best way in your opinion to find new ideas for games? I want to invent something really new (like Gish, World of Goo, Crayon Physics etc), but I'm having problems coming up with new, creative ideas.




textures - Painting terrain with a selection circle


I don't mean putting a circle under a unit like done in an RTS, that's fairly simply done with a scenegraph(-like structure). What I'm referring to is selection circles for things like Area of Effects that are painted on the terrain.


It seems relatively simple until I think about it.


Here are some images for reference:


http://i.stack.imgur.com/iXWXB.jpg http://im.tech2.in.com/images/2009/jan/img_116282_initialthreat_640x360.jpg


The first image gets the idea across, but not the full scope. Basically, the floor is painted with a decal detailing the region that will be affected by the spell.


The second image gets it across much better, it's not just a flat painted circle, it wraps along the mesh.


At first I figured to use some sort of object selection, and then in the vertex shader draw the texture on the correct vertices based on... some criteria that I'm still working out. Most likely based on distance and angle from the intersection point. The difficulty seems to come in that the methods wrap onto objects that seem to be completely different meshes.


I can't find an image that shows it (and don't play WoW anymore so I can't take a screenshot), but say you have a terrain mesh and a house on top of it and I select a point very close to the house's wall. Instead of continuing on the terrain mesh, the selection circle will go as far along the terrain mesh as it can, and then wrap up onto the wall of the house. It also ignores certain objects (players, etc), but that's pretty easy to ignore with correct collision tags/callbacks.


It's not so much that I can't think of a way to do this, but all the ways I can think of would probably lag your game out or turn your processor into slag. Somehow I have to:




  1. Draw a texture

  2. With no breaks

  3. Wrapping on multiple objects according to the terrain

  4. Centered at a given point

  5. Completely dynamically (so no pre-baking it into a bunch of dummy textures)

  6. Quickly enough to be computed every frame


Is there a standard method for this? Am I just overthinking it?


My best guess is rather than do one ray cast and selecting that point as the "center" I do a bunch of casts and in each case select the nearest vertex and bind the appropriate UV coord to that vertex, but it seems messy and potentially performance heavy to select that many vertices that way at the CPU frame-by-frame level. Especially since ray casts in general are expensive, even with a good physics engine.



It also doesn't seem particularly portable to anything other than a selection circle. A similar case would be like drawing the movement arrow over the terrain in Total War games, a thick arrow is drawn between the unit and its destination (see here: http://webguyunlimited.com/pixelperfectgaming/wp-content/gallery/total_war_shogun_2_rise_of_the_samurai/total_war_rots_screenshot_014.jpg ), this would seem to be a very similar technique to the AOE selection circle, but the ray cast method I mentioned wouldn't really work for it. There are, of course, numerous other examples too (such as trajectory markers).



Answer



Overthinking is an understatement! In your case it's especially easy, just Offset and Scale.


To get an orthogonal projection looking down Y axis, simply discard Y component. Your (unprocessed) texture coordinate [X,Y] is your world position [X,Z]. Now offset, scale, and limit to control the effect.


Here is a pseudo GLSL example of an effect like the one in your links:


        // These should of course come from somewhere in your pipeline
vec2 SelectionPoint = vec2(0.5, 0.5); //Red X
vec2 SelectionRadius = vec2(0.3, 0.3); //White Box Radius
vec2 TopDownWorld = (ModelMatrix * gl_Vertex).xz; //Blue X


// This is a simplification of the projection, since you are axis locked.
vec2 ProjectedTexCoord = TopDownWorld;
ProjectedTexCoord -= (SelectionPoint - SelectionRadius);
ProjectedTexCoord /= SelectionRadius * 2.0;
vec4 ProjectedTexel = texture(SelectionTexture, ProjectedTexCoord);

//* Stop the texture from repeating forever
if (ProjectedTexCoord.x > 1.0 || ProjectedTexCoord.x < 0.0 ||
ProjectedTexCoord.y > 1.0 || ProjectedTexCoord.y < 0.0) {
ProjectedTexel.a=0.0;

}
/*///* A bit cleaner but less academic:
if (ProjectedTexCoord != fract(ProjectedTexCoord)) ProjectedTexel.a=0.0; //*/

// Alpha blend the projected texture onto the final pixel color
gl_FragColor = gl_FragColor * (1.0 - ProjectedTexel.a) +
ProjectedTexel * ProjectedTexel.a;

Note that ModelMatrix is NOT gl_ModelViewMatrix (which is ViewMatrix * ModelMatrix)


Now for an example: (red X is the selection, blue X is the pixel we are shading) world space and eye space Lets work through some now, we are the pixel shader for the blue X



[0.75, 0.0] is our world coordinate
[0.5, 0.5] is our selection point
[0.3, 0.3] is our box radius

\frac{[0.75, 0]-([0.5, 0.5]-[0.3, 0.3])}{2*[0.3, 0.3]} = [0.91\overline{6}, -0.\overline{3}]


Or Simpler: \frac{[0.75, 0]-0.2}{0.6} = [0.91\overline{6}, -0.\overline{3}]


This gives our texture coordinate as [0.916, -0.3], which has a Y component less than zero, so the pixel is hidden using alpha=0. Although the X component is inside the box, near the edge (as you can see in the picture)




Now lets follow our selection point, which should clearly be right in the middle of the texture:


\frac{[0.5, 0.5]-0.2}{0.6} = [0.5, 0.5]



and it is :)




One more, to drive the point home, is the top right corner of the box where the answer intuitively should be [1, 1] because it's the top right corner ;)


\frac{[0.8, 0.8]-0.2}{0.6} = [1, 1]


and again it is


java - Gravity stops when side-collision detected



Please, look at this GIF:


enter image description here


The label on the animation says "Move button is pressed, then released". And you can see when it's pressed (and player's getCenterY() is above wall getCenterY()), gravity doesn't work. I'm trying to fix it since yesterday, but I can't. All methods are called from game loop.


public void move() {
if (left) {
switch (game.currentLevel()) {

case 1:
for (int i = 0; i < game.lvl1.getX().length; i++)
game.lvl1.getX()[i] += game.physic.xVel;
break;

}
} else if (right) {
switch (game.currentLevel()) {
case 1:
for (int i = 0; i < game.lvl1.getX().length; i++)

game.lvl1.getX()[i] -= game.physic.xVel;
break;
}
}
}

int manCenterX, manCenterY, boxCenterX, boxCenterY;
//gravity stop
public void checkCollision() {
for (int i = 0; i < game.lvl1.getX().length; i++) {

manCenterX = (int) game.man.getBounds().getCenterX();
manCenterY = (int) game.man.getBounds().getCenterY();
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
boxCenterX = (int) game.lvl1.getBounds(i).getCenterX();
boxCenterY = (int) game.lvl1.getBounds(i).getCenterY();
if (manCenterY - boxCenterY > 0 || manCenterY - boxCenterY < 0) {
game.man.setyPos(-2f);
game.man.isFalling = false;
}
}

}
}
//left side of walls
public void colliLeft() {
for (int i = 0; i < game.lvl1.getX().length; i++) {
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
if (manCenterX - boxCenterX < 0) {
for (int i1 = 0; i1 < game.lvl1.getX().length; i1++) {



game.lvl1.getX()[i1] += game.physic.xVel;
game.man.isFalling = true;

}
}
}
}
}
//right side of walls
public void colliRight() {

for (int i = 0; i < game.lvl1.getX().length; i++) {
if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
if (manCenterX - boxCenterX > 0) {
for (int i1 = 0; i1 < game.lvl1.getX().length; i1++) {

game.lvl1.getX()[i1] += -game.physic.xVel;
game.man.isFalling = true;
}
}
}

}
}
public void gravity() {
game.man.setyPos(yVel);
}

//not called from gameloop: public void setyPos(float yPos) {
this.yPos += yPos;

}


Answer



Change the code that removes falling if he is on top of the block:


if (manCenterY - boxCenterY > 0 || manCenterY - boxCenterY < 0) 
{
game.man.setyPos(-2f);
game.man.isFalling = false;
}

To code that removes falling if he is on top of the block:


if (manAboveBlock && (manCenterY - boxCenterY > 0 || manCenterY - boxCenterY < 0)) 

{
game.man.setyPos(-2f);
game.man.isFalling = false;
}

This is treating the symptom and not the problem however. The problem is probably that when the right key is pressed next to a wall, for a split second the player moves inside of that wall and then is corrected by moving back outside the wall. While the player is clipping into the wall his isFalling value is set to false.


java - Is there a way to capture back button twice in same activity libgdx game


Can anybody tell me if there is a possibility to capture back button twice in same activity in libgdx. What i want to achieve is that if the user press back button once the game pause. if in the pause screen user press back key again so the level exit. This happens well in "Video" that is the built in app in android OS. During video play a if user press back button it toast to press back again to exit.


so I want somthing like this.


if (Gdx.input.isKeyPressed(Keys.BACK)) {

code to call game pause state



if (Gdx.input.isKeyPressed(Keys.BACK)){ //// is this possible?

game.setScreen(new Menu(game))


}

} else {
code to call game resume state

}


opengl - Efficient skeletal animation


I am looking at adopting a skeletal animation format (as prompted here) for an RTS game. The individual representation of each model on-screen will be small but there will be lots of them!


In skeletal animation e.g. MD5 files, each individual vertex can be attached to an arbitrary number of joints.


How can you efficiently support this whilst doing the interpolation in GLSL? Or do engines do their animation on the CPU?



Or do engines set arbitrary limits on maximum joints per vertex and invoke nop multiplies for those joints that don't use the maximum number?


Are there games that use skeletal animation in an RTS-like setting thus proving that on integrated graphics cards I have nothing to worry about in going the bones route?



Answer



Limiting the number of bone influences is common, yes. You can either 0-weight unused influences, or have a loop/early-out mechanism to skip.


As for whether it works for an RTS, I don't have a reference for you, but I imagine you're going to need LOD if working with a large number of characters on-screen, and also if those characters are small.


LODing skeletal characters is much the same as LODing anything else, except you'll probably want to LOD the bone influences and skeleton as well as the mesh.


For example, a low-ish level of detail might only use a single bone with the highest influence per-vertex (also known as "hard skinning").


You would probably also limit the number of bones in the skeleton for a low LOD model.


Finally - consider whether you ever need to render the characters close-up. You probably only want to model, skin and animate the characters for the closest view distance... certainly you don't want to be storing all the runtime data at a resolution far higher than you'll ever render. You might find that you just don't need more than a very basic skeleton and a couple of influences per-vertex for your situation.


Tuesday, June 27, 2017

grammaticality - Tend to be/become (tending)




  1. Over time students tend to be better at their skills.

  2. Over time students tend to become better at their skills.


Which is correct? Can we use present continues?



  1. Over time students are tending to be better at their skills.

  2. Over time students are tending to become better at their skills.



Answer




"Tend to" is similar to other compound verbs (like "go to eat" or "open to receive"). The form is tend + (verb infinitive).:



They tend to play outdoors.


He tends to make outrageous comments.


She tends to walk into people because she's busy texting.



and so on.


Tending is not as often used, possibly because "tend" by itself already indicates a trend. If you look up the use of "tending" you'll far more often find its other definition as the gerund form meaning "to give your attention to and take care of". It's more natural to simply say "tend to become" rather than "tending to become".


"Tend to be better" makes sense, but it's not a natural expression. "Tend to improve" is the more common way to say this, along with similar phrases (tend to progress, tend to increase, etc.). Examples:




Over time, their performance on proficiency tests tends to improve.


Over the past few weeks, the trainees have tended to improve their hand-eye coordination.


Last month the unemployment rate tended to increase, but this month it's been flat.



mathematics - How do I interpret the dot product of non-normalized vectors?


I know that if you take the dot-product of two normalized vectors, you get the cosine of the angle between them.



But if I take the dot-product of two non-normalized vectors (or one normalized, one not), how can I interpret the resulting scalar?



Answer



Others have pointed out how you can use the sign of the dot product to broadly determine the angle between two arbitrary vectors (positive: < 90, zero: = 90, negative: > 90), but there's another useful geometric interpretation if at least one of the vectors is of length 1.


If you have one unit vector U and one arbitrary vector V, you can interpret the dot product as the length of the projection of V onto U:


diagram of a dot product with a unit vector


Equivalently, (U · V) is the length of the component of V pointing in the direction of U. ie. You can break V into a sum of two perpendicular vectors, V = (U · V)U + P, where P is some vector perpendicular to U.


This is helpful for rewriting a vector from one coordinate system in terms of a different basis, or for removing/reflecting the component of a vector that's parallel to a particular direction while keeping the perpendicular component intact. (eg. zeroing the component of a velocity that would take an object through a barrier, but allowing it to slide along that barrier, or rebounding it away)


I'm not aware of a convenient geometric interpretation of the dot product when both vectors are of arbitrary length (other than using the sign to categorize the angle).


unity - How can I specify which enemies to spawn for each round in a tower defense?


I am making a TD game in Unity, and I would like to know the most common approach to spawning enemies each round. I have more than 200 rounds per map, just like Fieldrunners.


Is it some kind of hardcoding, say for 25 rounds and then repeat the same waves with harder enemies, or maybe logic/algorithm based on rounds, where it'll give number of enemies and type of enemies which will spawn in that round.


I have 8 type of enemies. I want to implement a function/equation which inputs round number and outputs "number of enemies" and "enemy type" keeping the difficulty level which is round numbers.


for e.g if input: 50th round, output: enemy type1, large no. of enemies, if the input: 2nd round, output: enemy type 1, less number of enemies





grammar - Do you say "I like apple" or "I like apples"?


When stating a general fact/preference on countable nouns, singular or plural is more suitable and natural?


Example 1 :



I like apple.


or



I like apples.



Example 2:



I like eating apple.


or


I like eating apples.




Answer



Compare




"I like apples", means you like eating apples generally.



and



"I like the apple" means you are focused on one particular apple and you like this apple. Maybe you just like its shape and color.



However,



"I like eating the apple" means you are currently in the process of eating a particular apple and you like eating namely this particular apple or, which is most unlikely and funny you eat a particular apple from time to time (you like eating this apple)




As you can see articles are important here, you missed them in a couple of places of your questions, in: I like apple. and I like eating apple.


In some cases it's context that determines countability, not the word itself. You can meet tricky examples with apple like these:



"I like eating many fruits, but my favorite of all is the apple." (In that sentence, I'm not talking about any particular apple, but the genus of apple as a whole)



"There's too much apple in this fruit salad"


In some case a word can be both countable and uncountable, like when it can mean category or subject as in the next example:



"I bought a basket full of fruit." (perhaps one kind of fruit, perhaps not)



"I bought a basket full of fruits." (various kinds of fruit)



Monday, June 26, 2017

syntax - "What it does is {VERB / to VERB / VERBing} ..."?


For these expressions



What a paper shredder does is tearing the paper/tear the paper in small pieces which can be easily disposed.


What he wants to do is to become/become a ballplayer.




Which of these two forms is correct here to become/become, tearing/tear?



Answer



There are several different ways of producing subordinate clauses:



  • with that ... that he becomes/should become a baseball player

  • with a marked infinitive ... [him] to become a baseball player

  • with an unmarked infinitive ... become a baseball player

  • with for + a marked infinitive ... for him to become a baseball player

  • with a gerund ... becoming a baseball player



Each lexical verb 'licenses' (permits) some of these, but not all. Want, for instance permits:



  • He wants to become a baseball player ... with an implicit subject = the subject of the main clause

  • I want him to become a baseball player ... AND

  • I want for him to become a baseball player ... with a different subject


But you may not say



  • I want that he should become a baseball player.

  • He wants become a baseball player.


  • He wants becoming a baseball player ... and so forth.


And when you move the pieces around to create what grammarians call cleft constructions, like your What sentences, you have to follow the requirements of the verb, as in What he wants ... is to become.


Do is a little tricky, because it's not ordinarily a main verb; but with other verbs it acts like a modal, taking an unmarked infinitive: Yes, the paper shredder does cut the paper into small pieces. That's why, in your example, you may use either to become to agree with wants or unmarked become to agree with do. In the other construction, though, there is no such ambivalence, and you want the unmarked infinitive:



  • What the paper shredder does is tear the paper into small pieces.




marks an utterance as unacceptable


java - Simple way to serialize save game data whilst allowing for future features


Is there a simple way to 'serialize' the game data of my game, but protected it from being unloadable if I add new fields? I have all the data in a single class, GameData.java, and I want to avoid having to manually read/write each field from it. If I serialise it using standard java function, but add new fields to the class, it will render it unserializable.


I'd like to be able to save the class and the reload it from a file, and it use default values for any new fields that are missing from the save file. XML may be a solution, but is there an existing library to automate the process?


Thanks!



Answer




I use the libGdx Json functionality to save my game state to JSON;


public class GameInstance
{
//Some fields, constructors, utilities

public void saveState(GameState state)
{
String save = json.prettyPrint(state);

//Save to the file using FileHandle

}

public void loadState(FileHandle file)
{
String stateText = file.toString();
json.setIgnoreUnknownFields(true);
state = json.fromJson(stateText);
}
}


In my GameState I store the version of my app;


public class GameState
{
//some fields
public final String versionID = "0.1.1";

//game access functions
}

Before I access the modified field, I check to see if the versionID is correct and will allow me to read it. This allows me to write simple fallback mechanics that help provide as much of the new functionality as possible.




I keep a field-changes.txt file that I use to log changes that I make in my fields for each class. I almost never remove a field entirely for compatability reasons. When I do I try to add functions that can work out a suitable replacement value.


Now, without libGdx you can just use the Jackson JSON API(link to tutorial on how to use Jackson). The details can be found in this Stack Overflow question. In short, there is apparently an annotation that you can use that has this purpose in mind specifically.


The accepted answer says you should do this;


import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo
{
//...

}

Also check out the next best answer. Either way, the idea is still the same; to store the version of your GameState in each saved state and refactor the code to use the old data in alternative ways that makes the newest functionality possible.


Note: I only use libGdx and its Json library. Alternatively, if you wanted to use its Json library you could go and get the Json sourcecode. You would also need to copy the libGdx-specific collections and primitive collections to your project and fix the setup. You would have to do some minor editing to make it work.


3d - How To Make My First Person Controller turn left and right in unity 5


I want my first person controller to turn left and right instead of just moving straight on that axis.


i have a 3d environment setup in "unity 5" and i am working with the "first person controller" script in unity 5 by default it moves my camera forward,back,left and right what i want is to change the left and right so that it turns the camera instead of moving straight over.



Answer



What you want, is a rotation around the local y-axis when either A or D is pressed.


With the standard assets, this can be achieved quite easily, with the Input manager. To alter the settings, go to Edit->Project Settings->Input.
You should now see the settings for the Input in your Inspector window.



You want to change the Horizontal movement, so expand that and delete the Negative and Positive Buttons, as well as the alt buttons. Alternatively, you can set your preffered keys for horizontal movement. For Q and E, it would look like this:
Horizontal Input


If you look through the Settings, you can see a "Mouse X" setting. If you want to remove rotation with the mouse, you can directly edit this, or increment the Size field by 1. This will add another property at the end of the list, which you can edit.


Here are the important changes that need to be done, in order to work with the standard assets:



  • Name needs to be set to "Mouse X"

  • Negative and Positive Buttons need to be set, A and D in your case

  • Type has to be Key or Mouse Button


Also, you will probably want to set a high Gravity, so that the rotation stops quite soon, after releasing a key. You can also play around with the sensitivity, to get a faster or slower rotation.



The final input could look similar to this: Mouse X Input


algorithm - Smoothing found path on grid


I implemented several approaches such as A* and Potential fields for my tower defense game. But I want smooth paths, first I tried to find path on very small grid ( 5x5 pixels per tile) but it is extremly slow. I found nice video showing an RTS demo where paths are found on big grid but units dont move from each cell's center to center. How do I implement such behavior? Some examples would be great.



Answer



There's actually a pretty nice article about this at Gamasutra (7 pages!). While Beizer curves will smooth a path, it won't cut across grid spaces like in your video example.


For example (from the article):



  • (a) is the result of a standard A* search, while


  • (b) shows the results of a postprocess smoothing operation.

  • (c) shows the application of a turning radius for curved turns.

  • (d) illustrates an A* modification that will enable searches to include curved turns that avoid collisions.


4 images showing various topics discussed in the article


Must a complete sentence precede a colon?


Take this sentence:



I want the following: butter, sugar, and flour.




The part of the sentence that appears before the colon seems to not contain a noun; I seems to be an object, want seems to be a verb. There seems to be no object. It seems like it is a fragment? It seems all right to not place complete sentences after a colon... So maybe what goes before a colon doesn't have to be a complete sentence either?



Answer



A complete sentence does not have to precede a colon.


1 For example:


2 John: he was a real good friend until he stole my girlfriend.


3 Texas: It’s Like a Whole N'other Country.


3 Butter, sugar and flour: this is what I need to buy at the store.


4 Butter, sugar and flour: these are what I need to buy at the store.


5 Instructions: Assemble each light, hang the lights on the tree, plug in the power cord, turn the power switch on.



However, in your example:



I want the following: butter, sugar, and flour.



I want the following is a complete sentence. The subject is I and the verb is want. The direct object is the following.


Note: grammatically it is a complete sentence. Semantically, it may or may not suffice. For example, unless the writer or speaker says what he wants, it comes close to being an incomplete thought, which might wreck the idea that a sentence expresses a complete thought.


But, it could be said in real life, as in


I want the following and the person is going to tell you what he wants, but then the phone rings and he doesn't get a chance.


Sunday, June 25, 2017

xna 4.0 - How To Approach 360 Degree Snake



I've recently gotten into XNA and must say I love it. As sort of a hello world game I decided to create the classic game "Snake". The 90 degree version was very simple and easy to implement. But as I try to make a version of it that allows 360 degree rotation using left and right arrows, I've come into sort of a problem.


What i'm doing now stems from the 90 degree version: Iterating through each snake body part beginning at the tail, and ending right before the head. This works great when moving every 100 milliseconds. The problem with this is that it makes for a choppy style of gameplay as technically the game progresses at only 6 fps rather than it's potential 60.


I would like to move the snake every game loop. But unfortunately because the snake moves at the rate of it's head's size it goes way too fast. This would mean that the head would need to move at a much smaller increment such as (2, 2) in it's direction rather than what I have now (32, 32). Because I've been working on this game off and on for a couple of weeks while managing school I think that I've been thinking too hard on how to accomplish this. It's probably a simple solution, i'm just not catching it.


Here's some pseudo code for what I've tried based off of what makes sense to me. I can't really think of another way to do it.


for(int i = SnakeLength - 1; i > 0; i--){
current = SnakePart[i], next = SnakePart[i - 1];

current.x = next.x - (current.width * cos(next.angle));
current.y = next.y - (current.height * sin(next.angle));


current.angle = next.angle;
}

SnakeHead.x += cos(SnakeAngle) * SnakeSpeed;
SnakeHead.y += sin(SnakeAngle) * SnakeSpeed;

This produces something like this: Code in Action. As you can see each part always stays behind the head and doesn't make a "Trail" effect.


A perfect example of what i'm going for can be found here: Data Worm. Not the viewport rotation but the trailing effect of the triangles.


Thanks for any help!



Answer




With that algorithm, you're making each segment face the same angle as the one in front of it. That's why they all end up getting directly behind the head, they're ultimately all facing the same angle. As you can see in the Data Worm game you linked, each segment just faces toward the segment in front of it. Determine the angle from the current segment to its next and have the segment point that way instead of setting it to next.angle.


For that implementation, you may want to actually iterate from front to back instead. The behavior will be different based on the direction you pass through the list. Try them both and see which works better.


I've used a similar idea for a project prototype in the past (Unity WebPlayer link). I used similar (albeit 3D) code to get each segment to turn toward the segment in front of it and stay back a set distance. Worked like a charm.


pronouns - Can "it" refer to something we haven't mentioned yet?


We usually use pronouns to refer back to people or things that we already mentioned.


Can we use pronouns before we mention the noun?



A: Are you going to the game?
B: No, it's sold out. There aren't any tickets left.




Answer



As Rob K mentions in his answer: In your example A has already defined the context, so "it" is perfectly clear.


However, it is not uncommon to say a pronoun without context, but it is awkward since the listener would not know the reference. You would have to add some further explanation what you mean.




A. I'm sorry, it's completely sold out
B. What are you referring to?
A. The game. It's completely sold out.



I don't think this is unique to English, since it's more about the general quirks of pronouns or any ambiguous part of speech.


countability - "A paper", is this usage correct? Or should I say "a sheet of paper"?


I have a question:



  • "A paper", is this usage correct?

  • Or should I say "a sheet of paper"?




meaning - "Going to" vs. "going to go to"


What is the difference between the meanings of the following sentences?






  1. If I were going to Rome next week, I would be trying to find accommodation.




  2. If I were going to go to Rome next week, I would be trying to find accommodation.






I'm confused here, because i can see no difference in meaning between these two sentences.


"Going to vs going to go to"




tense - present continous or present perfect continous?


Should I write 'I have been reading a book now' or 'I am reading a book now'? I started to read one week ago and I haven't ended yet. Thanks for help




Saturday, June 24, 2017

c++ - Assimp and directX12 universal apps


I started a directX 12 universal app project on visual studios and started coding some stuff to create a physics engine. I was currently working on implmenting Assimp into the engine too load whatever 3d models I want. I believe I set the Assimp up incorrectly somehow. The code for loading the models worked on my last project with dx11 (non universal app). I will add the code anyways.


Mesh mesh;

// Create assimp importer to load the file
Assimp::Importer importer;
const aiScene* aiscene = importer.ReadFile(contentDirPath + filePath, aiProcess_OptimizeMeshes
| aiProcess_PreTransformVertices
| aiProcess_Triangulate
| aiProcess_GenSmoothNormals
| aiProcess_FlipUVs
| aiProcess_OptimizeGraph
| aiProcess_LimitBoneWeights);


// Append filePath to use file name as mesh name
mesh.name = filePath.substr(0, filePath.size());
mesh.name = mesh.name.substr(0, mesh.name.size() - 4);

for (UINT i = 0; i < aiscene->mNumMeshes; i++)
{
// Set the size of indices and vertices
mesh.vertices.resize(aiscene->mMeshes[i][0].mNumVertices);
mesh.indices.resize(aiscene->mMeshes[i][0].mNumVertices);


// Iterate through vertices
for (UINT j = 0; j < aiscene->mMeshes[i][0].mNumVertices; j++)
{
if (aiscene->mMeshes[i][0].HasPositions())
mesh.vertices[j].pos = XMFLOAT3(aiscene->mMeshes[i][0].mVertices[j].x, aiscene->mMeshes[i][0].mVertices[j].y, aiscene->mMeshes[i][0].mVertices[j].z);

mesh.indices[j] = j;
}
}


Now I think it has something to do with setting up the project. I went to Project->Properties->VC++Directories and in Executable, Include, & Library I added Assimp\bin, Assimp\include, and Assimp\lib respectively. Then in Project->Properties->Linker->Input->Additional Dependencies I added assimp.lib. I then included these into my project where needed. This is what I did for my non universal dx11 project and it worked fine.


#include 
#include
#include

Now when I run the program. I get this,



"Unable to activate Windows Store app 'App name here' The 'exe name here' process started, but the activation request failed with error 'The app didn't start'."



So I looked at the output and it says,




'A dependent dll was not found'



I checked to see if there was even a dll for assimp in the bin I added, there was. I also tried moving it to where the exe was located, that didn't work either. Am I doing something wrong? Does assimp not work in universl apps? If I comment out my assimp code and rebuild it runs fine so I figured the dll it said was not found was the assimp.dll




rendering - Self occluding object and alpha blending


Look at the object I've rendered with my app:


enter image description here



It's the same screen twice, above the original and below I've drawn (by hand :P) the shape of the mesh of one of plant's leaves. You can clearly see where the problem is.


From what I understand, this leave is drawn before the other leaves, writing a higher value to the depth buffer but not changing the pixel color (as it's transparent in that particular place). When the other leaves are drawn then their pixels in that place in the buffer are discarded since they're failing the depth test (they're farther away from the camera).


Now while I understand what the problem is I don't know how to solve it. This whole plant is one object so I can't sort by depth. What should I do?



Answer



While there is some interesting research into order-independent transparency rendering, it's extremely complex to implement. And even sorting individual leaves can still cause artifacts where one leaf overlaps itself. So your safest bet is probably Alpha Testing.


This is where you specify a threshold opacity value; anything above that value is rendered 100% opaque (and writes to the depth buffer), and anything below is not rendered at all (and does not write to the depth buffer - ensuring that other, occluded geometry can still be rendered there later).


Older graphics pipelines had a dedicated alpha testing phase for this. Newer ones often just use the discard command under the hood.


The trouble with this is that instead of soft translucent falloff, Alpha Testing gives you sharp aliased edges.


If your texture is relatively crisp-edged and you're usually a long distance from these surfaces, or you're using a post-process antialiasing filter anyway, then these jaggies should not look any worse than typical geometry silhouettes. You can probably stop here.


But if you can get close to the texture or your alpha falloff is very feathery, you'll often see jagged step artifacts.



Four approaches to rendering leaves


(Images excerpted from the Wolfire Games Blog. These show the artifacts better than the Unity docs image I was using earlier. Note the fringes in the top-left, incorrect sorting top-right, and aliased edges bottom-left. In the bottom-right, the foreground leaves still show aliasing where they overlap the trunk, but the texture detail makes this less noticeable than aliasing against the sky.)


One way to address these is to use a hybrid 2-pass shader. The first pass renders with alpha testing, to ensure proper z-sorting of the opaque portions. The second pass renders with alpha blending enabled and depth writes disabled, to fill-in the translucent fringes without creating the cutouts you see in the image in the original question, where depth writes from one leaf prevent the others from rendering fully.


The fringes can still visually intersect each other in incorrect ways due to the lack of sorting, but in practice this is often not very noticeable, especially in areas of high texture detail or similar colours overlapping.


A hat tip is due here to the awesome devs at Asteroid Base who introduced me to this hybrid strategy, used to great effect in rendering the enemy characters in Lovers in a Dangerous Spacetime.


Adjusting alpha cutoff value


Game Sound Effects Availability



Is there a need in the community for affordable game-focused sound effect packs? I am considering putting together some effects specifically geared toward games and indie developers that desire to get a working prototype quickly off the ground. Is there a need for this, or is there another standard "go-to" spot for this kind of thing? I want to offer value to the community but wanted to assess the need first. If anyone has thoughts, insight, or personal opinions on this I would love to hear it!




Turn-based Strategy Loop


I'm working on a strategy game. It's turn-based and card-based (think Dominion-style), done in a client, with eventual AI in the works. I've already implemented almost all of the game logic (methods for calculations and suchlike) and I'm starting to work on the actual game loop.


What is the "best" way to implement a game loop in such a game? Should I use a simple "while gameActive" loop that keeps running until gameActive is False, with sections that wait for player input? Or should it be managed through the UI with player actions determining what happens and when?


Any help is appreciated. I'm doing it in Python (for now at least) to get my Python skills up a bit, although the language shouldn't matter for this question.



Answer




Ok, if you don't care about the graphics, that's simpler. From a high-level pseudocode, what I suggest is like how any other game loop works:


while game has not ended yet:
keep going

// we're out of the while loop; game has ended
show results, etc.
go back to main menu

Thing is, yours is turn-based, so we can do away with the loop part, or keep it and use coroutines. Let's keep it simple for now though. (Not sure if standard Python has coroutines built-in)


So instead of a loop, we'll basically use callback functions.



The entry point for starting our game would be like this (this is still pseudocode):


// call this at the start of the game
function OnStartTurn()
{
currentPlayer.OnBeginTurn();
}

// call this function when the human player clicks on "End Turn" button, or if the AI decides it's finished.
function OnCurrentPlayerEndTurn()
{

change currentPlayer variable to the next player in line
OnStartTurn(); // will cause the next player to begin his turn
}

So from here, you can gather that we at least need a currentPlayer variable, which means we need some sort of Player class.


Also since we need to let the game pass control to the next player in line, we need to store all Player objects in a list (ordered in the way we want to). And on the OnCurrentPlayerEndTurn function, we simply cycle through that list so that the next player now begins his turn.


In OnStartTurn() we have a currentPlayer.OnBeginTurn(). You will want that for human players, this function will activate the GUI so the user can now act. For AI players you will want this function to start the AI's thinking process instead.


If you don't know how to do that, you have to learn polymorphism and object-oriented programming concepts.


Now for the human player, you'd provide some "End turn" button, which when clicked will call that OnCurrentPlayerEndTurn() function. For the AI, you'll want that immediately after the AI is done thinking and acting, it will likewise call OnCurrentPlayerEndTurn().


The idea is, either way, OnCurrentPlayerEndTurn() needs to get called in the end, so that the next player who needs to move gets his turn.



Unless a player won, in which case you don't need to bother calling that. Just go ahead and call your function to show results, etc.


How to capitalize (or not) an abbreviation, is there any rule?



Reading this article I was quite puzzled about the way the author capitalized or not the abbreviations.


When writing in full:



The Internet Corporation for Assigned Names and Number



All words are capitalized, but when abbreviating only the first letter is capitalized:



The Internet Corporation for Assigned Names and Number (Icann)



Following the article, there is an opposite situation:




generic top level domain.



Here, on the contrary the first letter is not capitalized while the rest are:



generic top level domain (gTLD).



Could you please explain if there are some rules on how to capitalize the abbreviations or it’s up to the author’s want?



Answer



This is, at least in part, a question of style. Or the style guides of, say, news organizations.




  • When you pronounce it as single letters, such as CNN (see en en) or BBC (bee bee see) it is usually written all caps.

  • When you pronounce it as one word some organizations write only capital letters, some spell it like a proper noun, first letter capitalized, rest lower case: CNN writes NATO, BBC writes Nato, as you say nato, not en ay tee oh.

  • There are lots of exceptions. SCSI is pronounced like a word, SKUZ-ee, but spelled upper case by the BBC, too.


auxiliary verbs - Why is "I'll be", wrong as a short answer?


I was writing a text in English to an Italian girl friend of mine whose English is very good. In the text, I asked:




Will you be coming to the staff party on Thursday?



and she replied



Yes, I'll be



I couldn't shrug and ignore it, I had to say something, so I texted back



You should've written: I'll be there :)




But she explained



Given that your question was: "Will you be coming...?" I thought that answering "I'll be" would be correct.



What do I tell her?!?


If the original question had been "Are you coming on Thursday?" or "Can you come on Thursday?" the answers:



(Yes,) I am
Yes, I can




would have been OK.



  • What's the grammatical explanation, or rule, that says I'll be (or I will be) is wrong when a question begins with the auxiliary will?



Answer



Heh, I think you answered your own question in your own question. It's wrong precisely because it's a response with an auxiliary verb, and therefore, we do not repeat the other verb in the short response. In other words, she should have said, "Yes, I will."


See Yes/No Questions, Auxiliary Verbs


And to predict your next question, no, she cannot say, "Yes, I'll."


But for this one, I'm not sure why other than to tell you, it's just wrong and sounds wrong.


Friday, June 23, 2017

How can I get involved with open source game projects?



I have a limited experience in game development and would like to get involved with open source game project. Where should I look and how should I begin?



Answer



Without referring to any of my previous projects, I can say that I've been involved with a great deal of open source activities, game-related and otherwise, and by and large I have thoroughly enjoyed the ride. Right now I'm a manager with the jMonkeyEngine project. I'll be glad to type up somewhat of an 'introduction to open source games', but bear in mind this will by no means be an exhaustive list of resources.


I highly recommend checking out similar pages for all of the links I provide.


Free, open source etc. - The subtle differences


It's worth merely noting that there are some differences to terms like 'free' (vs 'gratis'), 'open source', and 'free software'. The GNU project has a good but somewhat one-sided take on it, titled Open Source Misses The Point. Simply put though, I'd say the most damaging misconception about open source is that you're not supposed to make any money off of it.


Point is, even if you're giving away your code as well as your art assets (though copyrighted art assets could be a good way to make an essential part of your game proprietary, without really damaging its technical 'openness') for free, that doesn't mean you can't commercialize other parts of your project.



There's another gamedev thread here that'll hopefully bring in many good ideas on how to commercialize a free game.


Independent preparation


If you want to sharpen your talents before getting involved with a group of fellow developers, 'try make your own game' is a no-brainer, and there's no shortage of open source engines (see devmaster.net/engines and wikipedia.org/wiki/List_of_game_engines). If you're looking for a little motivational push though, there's nothing like a little bit of competition:



  • Ludum Dare - Frequently hosted 48h game competitions.

  • GameJolt - Infrequently hosts uniquely themed competitions. You can also upload your finished games there for free promotion.

  • GameCareerGuide's Game Design Challenges - Although not always requiring programming, GCG's weekly challenges open up a lot of opportunity for networking and unique concepts.


Find a project


There are plenty of places to look, and it's been a while since I was on the lookout, but I reckon most of the hobbyist projects (because that's what every open source game project is right now) make an appearance at either of these waterholes:




Choose a project


Choosing the right project that matches your particular skillset and interests (no one's gonna want to work with you if you're not enthusiastic about the game you're making) can prove to be quite the challenge. Take your time, and for the love of all that is good pick (or start, but I'll get back to that) a project that looks perfectly achievable within just a couple months time, at most. There are disappointingly few of these around, but for a first-time open source project it comes highly recommended.


Extra pointers:



  1. Don't start out too picky; look in different sites, consider odd genres, get to know the width of your skill-sets and interests.

  2. Consider scope. How much time are you willing to commit? How soon do you want to see the project finish? Any pending time-sinkholes (studies, work, life commitment) worth factoring in?

  3. Start by talking. Exchange at least 1000 words with someone involved in a given project before finally making up your mind.

  4. Now stick with it and bring it to the finishline!



A great thing about open source projects is the low barrier to entry. There's loads of ways to contribute to a project besides applying your key skills. Just look at the CONTRIBUTING.md of any major project on GitHub for examples.


Honestly, the 'open source games' complete/incomplete ratio could use a boost. The beauty of transparency and open source though is that 'incomplete' is far from 'unsuccessful' so long as you make the most out of the ride.


Update: Also see my closely related article on opensource.com, which is based on this answer.


java - Box2D platformer movement. Are joints a good idea?


So i smashed my brains trying to make my character move. As i wanted later in the game to add explosions and bullets it wasn't a good idea to mess with the velocity and the forces/impulses didn't work as i expected so something stuck in my mind: Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation? I will attach this to my main body with a revolute joint but i don't really know how to make the main body and wheel body to don't collide one with each other since funny things can happen. What is your oppinion?



Answer




: Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation?



That is exactly what you should. I once wrote a tutorial on it for C#/XNA and Farseer, but you should be able to adopt it easily to Java and Box2D (Farseer is based on Box2D).


Here's the tutorial:


http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/



The end result should be something like this: Platformer


And a video: http://www.youtube.com/watch?v=iC_Y9Tq5JeU&feature=player_embedded


Meaning of a sentence in the Gilmore Girls S1E10


I want to ask about the meaning of a sentence.



RICHARD: Ah. Speaking of which, I’m going to give that man a call.


ALAN: Richard, you’re getting yourself all worked up.


RICHARD: As long as I’ve been with this company, it has been run by gentlemen. Revising a man’s work without so much as a phone call would’ve been unheard of!



The sentence that I don't understand is "Revising a man's work ... would've been unheard of!". I guess Richard is saying that giving a phone call is not a big deal. But I am not exactly know how to analyze the sentence. First, what does "so much as" mean here? I find two meaning for phrase. Merriam- Webster says it means "even" and Cambridge says it means "but rather". Which is more suitable here? Second, what does Richard mean when he says "would've been unheard of!"?




Answer



"Without so much as a ___" means that an action was performed without the bare minimum of response. "He took all of my birthday cake without so much as a thank you!" (He probably should have done much more than say thank you, but at least that!)


http://dictionary.reference.com/browse/without-so-much-as


for something to be "unheard of" means it's out of the realm of possibility. "Why, for a bride to wear a bathing suit to her wedding? That's unheard of!"


http://www.thefreedictionary.com/unheard-of


All together:


"This company used to be run by nice people. Now, someone is revising this man's work and not even bothering to do the bare minimum of giving him a phone call to tell him! That never would have happened in the past!"


performance - Is SVG a viable technology choice for web-based game?



I have started to read up about the web technology available for doing web-based game with only Javascript, but I have no where got feedback about SVG with HTML5. Is is a viable choice ? Does it performs well compared to other technique like Canvas, DOM & CSS Transformation, etc.



Answer



SVG is supported in HTML5; whether the browser your player is using supports it is a different story.


Depending on your needs you should check out RaphaelJS. Raphael provides SVG-like support for IE by switching to VML when rendering for IE. Raphael provides a lot of functionality including animations and Cufon font support. It's definitely worth a look.



Since SVG is a part of the DOM it is pretty simple to attach DOM events like "click" and "hover" to the created SVG elements. This might make SVG more suitable for HUD-type displays rather than animating sprites, etc.


You probably have a lot of testing ahead of you to determine the relative performance characteristics of SVG versus canvas, however.


Straight DOM manipulation will probably be the worst of the bunch. As you change things in the DOM the browser's layout engine will recalculate the layout of the page to accomodate your changes which will probably kill your game's performance. If you have to go this route, prefer CSS (especially CSS3-specific features like transformations and keyframing).


adverbs - Does "It snowed hard Monday" require an "on"?


I came across an English learner writing



It snowed hard Monday.



After saying that it didn't snow on Friday and Saturday.


It didn't quite feel right to me.


I'd be okay with




It snowed hard.



or



It snowed Monday.



Is it okay for there to be two things ("hard" and "Monday") modifying the snowing without an "on" breaking things up a bit?



Answer



In North American Engish, Monday can be used as adverb to mean on Monday, in the same way Mondays is used to mean on Mondays, on each Monday.


I have looked for sentences similar to the ones shown in the question on the Corpus of the Contemporary American English, and I found the following ones. (I looked for sentences containing "[vvd] hard [npd1]"; that is the COCA's way to look for sentences containing "[past tense] hard [weekday]" where the part between brackets is a token that allows to precisate the category of the word.)




We're going to check in now with a couple of towns that have really borne the brunt of the Flood of' 93. The Quincy area, Quincy, Illinois, and West Quincy, Missouri, hit hard Friday night when an important levee broke there.




We skied hard Saturday to clear our bodies of Friday night's brewtasting toxins.




"In my mind, they make up for some of the balls I hit hard Friday night that were right at people," Ripken said.



The Corpus of the Contemporary American English has a total of three sentences that match the search terms "[past tense] hard [weekday]" (1 in the "spoken" section). It doesn't have any sentence matching "[past tense] hard on [weekday]" or "[past tense] hard [preposition] [weekday]."



As comparison, there are 215 sentences matching "[past tense] [adjective] [weekday]" (43 in the "spoken" section), and no match for "[past tense] hard [preposition] [weekday]." In the first case, there are sentences containing "came late Sunday," "called late Thursday," or "came clean Monday."
There are also 16 sentences matching "[past tense] on [adjective] [weekday]" (5 in the "spoken" section), with sentences containing "came on Super Tuesday," "shopped on Black Friday," or "attended on Good Friday."


sdl2 - Render to texture and then to screen cause flickering


So I have my class vItem which has a vector (consider elements like layers) of textures, origin rects and destination rects plus other stuff.
Basically whenever I update any of the layers in the vector I redraw everything on an internal texture which is then displayed on the screen, here's the function that draws on the texture:


void vItem::draw(){
if(sprites.size() <= 0)
return;


// This calculates the dimensions of a rectangle big enough to contain every texture
SDL_Point size = calculateSpriteRect();

if(size.x <= 0 || size.y <= 0)
return;

// If the final texture does not exists or its dimensions are different from the new rectangle I destroy it and recreate it
if(final_sprite == NULL || size.x != final_sprite_size.x || size.y != final_sprite_size.y){
if(final_sprite != NULL)

SDL_DestroyTexture(final_sprite);
final_sprite = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, size.x, size.y);
SDL_SetTextureBlendMode(final_sprite, SDL_BLENDMODE_BLEND);
final_sprite_size = {size.x, size.y};
}

SDL_RenderPresent(renderer);
SDL_SetRenderTarget(renderer, final_sprite);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);

for(int i = 0; i < sprites.size(); i++){
SDL_SetTextureAlphaMod(sprites[i].sprite, sprites[i].alpha);
SDL_RenderCopy(renderer, sprites[i].sprite, &sprites[i].source, &sprites[i].bounds);
}
SDL_RenderPresent(renderer);
SDL_SetRenderTarget(renderer, NULL);
}

The problem comes after this function: I have a child class of vItem called vButton where I have two layers of text (one normal and the other on for when the mouse is over the button), and when I update alpha values of the layers to hide one level and show the other one draw() is called. This transition causes an instant flickering (black background right before drawing).
When I removed vSync I noticed that this wasn't happening anymore, but I need vSync.



UPDATE:
Ok... Apparently if I remove both SDL_RenderPresent(renderer); the flickering is gone and everything is rendering correctly, but I can't understand why. This is the final function:


void vItem::draw(){
if(sprites.size() <= 0)
return;

// This calculates the dimensions of a rectangle big enough to contain every texture
SDL_Point size = calculateSpriteRect();

if(size.x <= 0 || size.y <= 0)

return;

// If the final texture does not exists or its dimensions are different from the new rectangle I destroy it and recreate it
if(final_sprite == NULL || size.x != final_sprite_size.x || size.y != final_sprite_size.y){
if(final_sprite != NULL)
SDL_DestroyTexture(final_sprite);
final_sprite = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, size.x, size.y);
SDL_SetTextureBlendMode(final_sprite, SDL_BLENDMODE_BLEND);
final_sprite_size = {size.x, size.y};
}


//SDL_RenderPresent(renderer);
SDL_SetRenderTarget(renderer, final_sprite);
//SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
//SDL_RenderClear(renderer);
for(int i = 0; i < sprites.size(); i++){
SDL_SetTextureAlphaMod(sprites[i].sprite, sprites[i].alpha);
SDL_RenderCopy(renderer, sprites[i].sprite, &sprites[i].source, &sprites[i].bounds);
}
//SDL_RenderPresent(renderer);

SDL_SetRenderTarget(renderer, NULL);
}

How can the renderer keep information about the texture on texture rendering and texture on screen rendering at the same time (since I have only one SDL_RenderPresent() left at the end of my game loop)? Is it meant to work like that?




word choice - Do we say something for affect or effect?


Do we say something for affect or effect?


For instance, if I give the description of a round ball, it seems that the word round is redundant; however, I have chosen to combine those words "for affect/effect"?


In researching this, all I could find is the usual definitions of affect and effect: affect is a verb and effect is a noun; however, in with my understanding of English, it seems that they can be used interchangeably in the aforementioned phrase?



Answer



No, they are not interchangeable. Here, for takes a noun, not a verb (bare infinitive). So your choices are the nouns affect and effect. Affect (noun) is uncommon (in everyday use). It seems to be a psychological term given. The dictionary gives




affect
1. the conscious subjective aspect of an emotion considered apart from bodily changes; also : a set of observable manifestations of a subjectively experienced emotion <… patients … showed perfectly normal reactions and affects … — Oliver Sacks>



This doesn't match the desired meaning. The answer is effect (noun):



effect
7. b : the creation of a desired impression <her tears were purely for effect>



So in your example, you want to say round ball for the creation of a desired impression, whatever that may be.


xna - C# Perlin noise - generating “endless” terrain chunks?



I'm currently writing a little side scroller in C#, to both learn C# and have fun. Right now I have a simple random number generator generating the world but it isn't exactly all that great - so with some research, I've discovered that Perlin Noise generation may help me out quite a bit. Problem is, I want to have an "endless" landscape made up of several chunks.


Basically my questions / concerns are:



  1. Using minecraft as an example (Ignoring the 3rd dimension), how is Notch getting each chunk to connect to each other perfectly? Tunnels, caves, ore veins, mountains, flat lands, biomes, etc. are all connected to each other even though each chunk is generated separately, and sometimes at a much later date. This is key for me, I want the player to be able to walk to the right and as they are walking, generate more landscape that connects to previous landscape, including underground tunnels and cave systems.

  2. Going off of #1, how would this be accomplished under the assumption that each chunk is a square, and the world is 10 squares high, and infinite squares wide? I.e. Each "chunk" is 128x128 tiles and the world is 1,280 tiles tall total. (This is so that I can make an infinitely deep map if I choose to - and also to show that all 4 sides of a chunk / square need to be able to connect and continue on what the previous square/chunk was doing).



Answer



Find a C# implementation of Simplex Noise, it's like Perlin but better behaved and faster.


The thing about continuous noise functions like Perlin and Simplex is that they are deterministic, noise is not random. What most noise implementations use is a Seed value that offsets into the noise generated which makes Seed=1 different from Seed=2.


Because of the above observation you can keep reusing the Seed and all the new terrain generated as you move through the noise function will match up because it just picks up where you left off.



This part of it is pretty simple and quite nice, what you do with the generated noise is where the magic happens.


To James, that's possible but my personal speed test with a 3D noise showed simplex to be faster at 3, could be any number of factors in my personal test but it matched the general idea in literature. Even if it were slower I would recommend simplex because it doesn't show the "square" artifacts that perlin does.


To Jon, Noise is a math function and it just spits out results from parameters and given the same parameters you will get the same number back. I see where the confusion might come from.


This noise function is sampled like: number=noise(x,y,z); for 3 dimensional noise. As an example, your first map may sample from X=0.0 to X=1.9, the map just to the right of it continues and samples from X=2.0 to 3.9


Part of the art of using noise is finding good ranges to sample, deciding on how many octaves, filtering and processing etc... Take a look at a handy noise library to see a few examples and some source code of Perlin in action.


javascript - How can I clear explosions in my function?


Hi I have a function to place bombs, and a for loop that places explosions on the tiles where possible.


My problem is that I can't remove the explosions after a while. I've tried everything I can come up with so now I turn here as a last resort.


The function looks like this:



function Bomb(){
var placebomb = false;
if(placeBomb && player.bombs != 0){
map[player.Y][player.X].object = 2;
var bombX = player.X;
var bombY = player.Y;
placeBomb = false;
player.bombs--;
setTimeout(explode, 3000);
}

function explode(){
var explodeNorth = true;
var explodeEast = true;
var explodeSouth = true;
var explodeWest = true;

map[bombY][bombX].explosion = 1;
delete map[bombY][bombX].object;

for(i=0;i<=player.bombRadius;i++){

if(explodeNorth && map[bombY-i][bombX]){
if(!map[bombY-i][bombX].wall){
if(!map[bombY-i][bombX].object){
map[bombY-i][bombX].explosion = 1;
}
else
var explodeNorth = false;
delete map[bombY-i][bombX].object;
map[bombY-i][bombX].explosion = 1;
}

else
var explodeNorth = false;
}

if(explodeEast && map[bombY][bombX+i]){
if(!map[bombY][bombX+i].wall){
if(!map[bombY][bombX+i].object){
map[bombY][bombX+i].explosion = 1;
}
else

var explodeEast = false;
delete map[bombY][bombX+i].object;
map[bombY][bombX+i].explosion = 1;
}
else
var explodeEast = false;
}

if(explodeSouth && map[bombY+i][bombX]){
if(!map[bombY+i][bombX].wall){

if(!map[bombY+i][bombX].object){
map[bombY+i][bombX].explosion = 1;
}
else
var explodeSouth = false;
delete map[bombY+i][bombX].object;
map[bombY+i][bombX].explosion = 1;
}
else
var explodeSouth = false;

}

if(explodeWest && map[bombY][bombX-i]){
if(!map[bombY][bombX-i].wall){
if(!map[bombY][bombX-i].object){
map[bombY][bombX-i].explosion = 1;
}
else
var explodeWest = false;
delete map[bombY][bombX-i].object;

map[bombY][bombX-i].explosion = 1;

}
else
var explodeWest = false;
}

}
player.bombs++;
}

}

If anyone can think of a good way to remove the explosion after a delay please help.



Answer



Have you tried creating an Explosion object with its own lifetime? If you add the explosion tiles that you place to an array that's managed by some sort of supervisor, then you could add a setTimeout(manager.deleteMe(X,Y), 100) in an Explosion object.


Thursday, June 22, 2017

Best practices for labeling game versions?


Does anyone know if there's a best practice for labeling game versions.


I'm not sure if there's a standard name for it other than versioning but what I mean is basically:



  • 1.0

  • 1.1


  • 1.2

  • 1.3.1 beta



Answer



There is no standard, but you should do it in a way that makes sense to you and contains all the information you may need to track that build. I worked for a company that essentially broke it down like this:


[Major build number].[Minor build number].[Revision].[Package]


i.e. Version: 1.0.15.2




  • Major build number: This indicates a major milestone in the game, increment this when going from beta to release, from release to major updates.





  • Minor build number: Used for feature updates, large bug fixes etc.




  • Revision: Minor alterations on existing features, small bug fixes, etc.




  • Package: Your code stays the same, external library changes or asset file update.





Combined changes roll over to the most significant change. For example, if you're incrementing the minor build number, the revision and package both reset to 0.


Even though the categories are defined, there's still ambiguity for what kind of features actually cross over between a revision and a minor build number. It's up to you. If you make lists of the features that will need to be implemented before each increment, you'll also have a plan to follow, but in the end it's your decision as to what fits into each category.


Can we use the phrase "so-called" in its positive sense (or neutral) when refereeing to a widely adopted thing?


Let's consider the context below:



  • we have an "old technique" which is widely adopted by several researchers. now, you propose a new one.


you might say:




We propose a new technique under which fault analysis becomes more tractable than the so called "old technique".



My question is that weather or not I can use "so-called" in such a context. I was thinking to "widely accepted" or "broadly adopted" though. However, this question struck my mind.



Answer



To me so-called means it is contested. (His so-called wife is really a paid escort.) It can be used to express one's opinion that a name or term is inappropriate. It doesn't always mean a negative, but your audience would need to know your context to understand it.


So if you want to be certain that your comment is not seen as a negative one, use your other phrases instead. Both "widely accepted" or "broadly adopted" work.


Wednesday, June 21, 2017

pronouns - "It may have been her brother" Why do we use IT instead of HE?


I read the following in English Grammar in Use book (app):



Who was the man we saw with Anna yesterday?


I don't know. It may have been her brother.



Why do they use "it" instead of "he"?


Generally, when do we use "it" instead of "he" or "she"?


Update:



So, Does It use here as an empty (dummy) subject, or as pronoun of unidentified person?



Answer



This is a dummy it or anticipatory it. We often use it to refer to facts or the existence or nature of something. Every English sentence must have a subject, but sometimes when we're talking about the nature or existence of something, we use it as a placeholder subject. For example,



It is raining.
It was good to see you yesterday.
It was Janet at the door.



In that last example, saying "She was Janet at the door" is wrong, because we're really talking about a fact or a phenomenon, not the nature of a particular female person; we use it to anticipate the fact that is revealed later in the sentence.


References:




java - How can I make a sprite-sheet-based animation system?



I want to make animations based on a sprite sheet, but I'm stuck implementing it.


The key things I need my code to do are:



  • Play through a set of images once (e.g. a jump animation)

  • Loop through a set of images continuously (e.g. a walking animation)


  • Change an animation's speed


How can I implement such a system?




xna 4.0 - Cutting out smaller rectangles from a larger rectangle


The world is initially a rectangle. The player can move on the world border and then "cut" the world via orthogonal paths (not oblique). When the player reaches the border again I have a list of path segments they just made.


I'm trying to calculate and compare the two areas created by the path cut and select the smaller one to remove it from world.


After the first iteration, the world is no longer a rectangle and player must move on border of this new shape.


How can I do this? Is it possible to have a non rectangular path? How can I move the player character only on path?



EDIT


Here you see an example of what I'm trying to achieve: 5 phases of a rectangle being cut smaller by other rectangles




  1. Initial screen layout.




  2. Character moves inside the world and than reaches the border again.





  3. Segment of the border present in the smaller area is deleted and last path becomes part of the world border.




  4. Character moves again inside the world.




  5. Segments of border present in the smaller area are deleted etc.






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