Monday, July 31, 2017

physics - In a 2D platform game, how to ensure the player moves smoothly over sloping ground?


I'm developing a physics engine for a 2D platform game. I'm using the separating axis theorem for collision detection. The ground surface is constructed from oriented bounding boxes, with the player as an axis aligned bounding box. (Specifically, I'm using the algorithm from the book "Realtime Collision Detection" which performs swept collision detection for OBBs using SAT). I'm using a fairly small (close to zero) restitution coefficient in the collision response, to ensure that the dynamic objects don't penetrate the environment.


The engine mostly works fine, it's just that I'm concerned about some edge cases that could possibly occur. For example, in the diagram, A, B and C are the ground surface. The player is heading left along B towards A. It seems to me that due to inaccuracy, the player box could be slightly below the box B as it continues up and left. When it reaches A, therefore, the bottom left corner of the player might then collide with the right side of A, which would be undesirable (as the intention is for the player to move smoothly over the top of A). It seems like a similar problem could happen when the player is on top of box C, moving left towards B - the most extreme point of B could collide with the left side of the player, instead of the player's bottom left corner sliding up and left above B.



Box2D seems to handle this problem by storing connectivity information for its edge shapes, but I'm not really sure how it uses this information to solve the problem, and after looking at the code I don't really grasp what it's doing.


Any suggestions would be greatly appreciated.





paddy field - is it countable or uncountable noun?



In some areas, **some fields could be found among the river, houses, etc.



Could I say "some paddy fields"?




opengl - Trouble applying a texture to a cube


Currently working on applying a texture to a cube and I am at a road block. I am using UV coordinates to apply the texture. Currently using 24 uv coordinates with indices. I am using glDrawElement and draw all 36 vertices. The cube in itself renders but the texture looks blurry and not accurate.


const GLfloat vertices[] = {

-0.5f, 0.5f, 0.0f, // Top Left
-0.5f, -0.5f, 0.0f, // Bottom Left

0.5f, -0.5f, 0.0f, // Bottom Right
0.5f, 0.5f, 0.0f, // Top Right

-0.5f, 0.5f, -1.0f, // Top Left (back)
-0.5f, -0.5f, -1.0f, // Bottom Left (back)
0.5f, -0.5f, -1.0f, // Bottom Right (back)
0.5f, 0.5f, -1.0f // Top Right (back)

};


const GLfloat color[] = {

0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f
};

const GLfloat texCoord[] = {


1.0f, 1.0f, 0.0f,
1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f

};

const GLfloat uvCoord[] =
{


0.0f, 1.0f, // Top Left
0.0f, 0.0f, // Bottom Left
1.0f, 0.0f, // Bottom Right
1.0f, 1.0f, // Top Right

0.0f, 1.0f, // Top Left
0.0f, 0.0f, // Bottom Left
1.0f, 0.0f, // Bottom Right
1.0f, 1.0f, // Top Right


0.0f, 1.0f, // Top Left
0.0f, 0.0f, // Bottom Left
1.0f, 0.0f, // Bottom Right
1.0f, 1.0f, // Top Right

0.0f, 1.0f, // Top Left
0.0f, 0.0f, // Bottom Left
1.0f, 0.0f, // Bottom Right
1.0f, 1.0f, // Top Right


0.0f, 1.0f, // Top Left
0.0f, 0.0f, // Bottom Left
1.0f, 0.0f, // Bottom Right
1.0f, 1.0f, // Top Right

0.0f, 1.0f, // Top Left
0.0f, 0.0f, // Bottom Left
1.0f, 0.0f, // Bottom Right
1.0f, 1.0f // Top Right



};

const GLuint indices[] =
{
// Front
0, 1, 3,
1, 2, 3,

// Back

4, 5, 6,
4, 6, 7,

// Left
4, 5, 1,
1, 0, 4,

// Right
3, 6, 2,
7, 6, 3,


// Top
7, 4, 3,
4, 0, 3,

// Bottom
1, 2, 5,
2, 5, 6



};


const GLuint VERTEX_POS = 0;
const GLuint COLOR = 1;
const GLuint TEX_POS = 2;
const GLuint UV_POS = 3;

GLuint VAO;
glGenVertexArrays(1, &VAO);

glBindVertexArray(VAO);

const int SIZE = 4;

GLuint VBO[SIZE];
glGenBuffers(SIZE, VBO);

// Handles position
glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glVertexAttribPointer(VERTEX_POS, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
glEnableVertexAttribArray(VERTEX_POS);

// Handles Color
glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(color), color, GL_STATIC_DRAW);
glVertexAttribPointer(COLOR, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
glEnableVertexAttribArray(COLOR);

// Handles Texture Coordinates

glBindBuffer(GL_ARRAY_BUFFER, VBO[2]);
glBufferData(GL_ARRAY_BUFFER, sizeof(texCoord), texCoord, GL_STATIC_DRAW);
glVertexAttribPointer(TEX_POS, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
glEnableVertexAttribArray(TEX_POS);

// Handles uv Coordinates
glBindBuffer(GL_ARRAY_BUFFER, VBO[3]);
glBufferData(GL_ARRAY_BUFFER, sizeof(uvCoord), uvCoord, GL_STATIC_DRAW);
glVertexAttribPointer(UV_POS, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), nullptr);
glEnableVertexAttribArray(UV_POS);


GLuint EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

GLuint Texture;
glGenBuffers(1, &Texture);
glBindTexture(GL_TEXTURE_2D, Texture);


glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

int texWidth;
int texHeight;
unsigned char * image = SOIL_load_image("brick_texture1.jpg", &texWidth, &texHeight, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);

glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);

In the loop:


        glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);

vertex shader:


#version 400 core 
layout (location = 0) in vec3 position;
layout (location = 1) in vec4 color;




layout (location = 2) in vec2 texCoord;
layout (location = 3) in vec2 uvCoord;

out vec4 out_color;
out vec2 out_texCoord;
out vec2 out_uvCoord;



uniform mat4 MVP;
uniform mat4 rotation_matrix;

void main()
{
out_color = color;
out_uvCoord = uvCoord;
out_texCoord = vec2(texCoord.x, texCoord.y);
gl_Position = MVP * rotation_matrix * vec4(position, 1.0f);

}

Fragment Shader:


  #version 400 core

in vec4 out_color;
out vec4 Output_Color;
in vec2 out_texCoord;
out vec2 Output_texCoord;


in vec2 out_uvCoord;

uniform sampler2D Texture;

void main()
{

Output_Color = texture(Texture, out_uvCoord);
}


The finale product: enter image description here enter image description here


I do not know what the problem might be.



Answer



The 5th "stride" argument in all of your 4 glVertexAttribPointer calls is specified as 3 * sizeof(GLfloat), while in your case it should be 0, as you are using separate buffers per vertex attribute (see https://www.opengl.org/sdk/docs/man/html/glVertexAttribPointer.xhtml).


That argument is non-zero for cases when you interleave those attributes in a single buffer, which is an interesting optimisation, see https://www.opengl.org/wiki/Vertex_Specification_Best_Practices, but I'd just change those arguments to 0 for now.


You're also using glDrawElements, which forces a different topology than you probably want to have, as the cube's faces share vertex positions, but not necessarily vertex uv mappings.


What the glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); call is doing, is taking only uvCoord with indices from the 0-7 range (as that's what your indices array contains) which don't correspond to the correct texture coordinates at most faces.


You'll find a good explanation of mesh topologies at http://alfonse.bitbucket.org/oldtut/Illumination/Tut09%20Mesh%20Topology.html, the whole tutorial is a great read.


To cut the long story short :)





  1. Define vertices as:


    const GLfloat vertices[] = {
    -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5,
    -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5,

    0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5,
    0.5, -0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5,

    0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5,

    0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5,

    -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5,
    -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5,

    -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5,
    -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5,

    -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5,
    -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5

    };


(This does what your indices sort of did, but in an explicit way)




  1. Define uvCoord as:


    const GLfloat uvCoord[] = {
    0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,


    0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

    0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

    0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,


    0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,

    0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f
    };


so each face has the same uv mapping.





  1. Replace the


    glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);


call with


glDrawArrays(GL_TRIANGLES, 0, 36);


  1. Comment out the indices binding (GLuint EBO;... and 3 following lines)



Hopefully it works, if it does then try to experiment with the uvCoord definition to obtain the texture mapping you need.


java - How should I implement card effects in a card game?


I've been trying to program a video game adaptation of the popular trading card game "Magic: The Gathering". If you've played MTG before, you'll know most cards have an effect, which is activated at a certain time, usually when it's played. But I'm unsure how to implement effects into my game.


I'm thinking of creating a method that assigns a card its effect when it's played based on the card's name, but that doesn't really work when a card's effect isn't supposed to be activated when it's played, like in the case of Deathrattle cards, or when it's a continuous effect. I've thought of creating a thread for each effect which activates it whenever needed, but... that's a LOT of unique threads. I haven't found any similar java programs anywhere, so I wanna ask here. How do you think card effects should be handled?




Answer



Threads would definitely be overkill here. I would use event listeners.


First, make an ICommand interface. (The param is so that you can optionally pass data to your command)


public interface ICommand{
public void execute(Object param);
}

Then make sure you clearly define every scenario in which a card will activate and create a ICommand variable in your Card class essentially creating a "slot" for each event type.


//Card class
ICommand onDeathrattleCommand;

ICommand onCardPlayedCommand;
//... other event types

When you create each card type, you initialize the appropriate event slots


Card deathrattleCard = new Card();
deathrattleCard.onDeathrattleCommand= new ICommand(){
public void execute(Object param){
foreach(Card opponentCard: opponentsCards){
opponentCard.applyDamage(6);
}

}
};

Then trigger these events at the appropriate time


//Card class
public void onPlayed()
{
if(onCardPlayedCommand != null){
onCardPlayedCommand.execute(null);
}

}

public void applyDamage(int damage)
{
hp -= damage;
if(hp <= 0 && onDeathrattleCommand != null){
onDeathrattleCommand.execute(null);
}
}

grammar - I have a problem with verb structure


In this sentence:




Four items are responsible for three-fourths of the overall spending around the world, the most prominent share being that of food.



Why after the comma, the verb "being" is used? Why it does not use "is"?



Answer



Your example is one sentence. It doesn't need to be:



Four items are responsible for three-fourths of the overall spending around the world.  The most prominent share is that of food. 



"Is" is a finite form. It creates a predicate and requires a subject.  "Being" is a non-finite form.  It creates a modifier. 



The entire structure "the most prominent share being that of food" is an absolute phrase.  It consists of the noun phrase "the most prominent share" modified by the following participial phrase "being that of food".  The absolute structure acts as a supplement to the associated clause, rather than acting as a clause on its own. 


c++ - Toggle Fullscreen at Runtime



Using the library GLFW, I can create a fullscreen window using this line of code.


glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0, GLFW_FULLSCREEN);

The line for creating a standard window looks like this.


glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0, GLFW_WINDOW);

What I want to do is letting the user switch between standard window and fullscreen by a keypress, let's say F11.


It there a common practice of toggling fullscreen mode? What do I have to consider?



Answer



I'm not sure about common practices, but lacking a glfwToggleFullscreen, this seems one way to toggle fullscreen mode:



// On input handling, check if F11 is down.
if ( glfwGetKey( GLFW_KEY_F11 ) ) {

// Toggle fullscreen flag.
fullscreen = !fullscreen;

// Close the current window.
glfwCloseWindow();

// Renew calls to glfwOpenWindowHint.

// (Hints get reset after the call to glfwOpenWindow.)
myGLFWOpenWindowHints();

// Create the new window.
glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0,
fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW);

}

Another method, this time for fullscreen windowed mode:



// Create your window in windowed mode.
glfwOpenWindow(originalWidth, originalHeight, 8, 8, 8, 8, 24, 0, GLFW_WINDOW);
glfwSetWindowPos(originalPosX, originalPosY);

// Get the desktop resolution.
GLFWvidmode desktopMode;
glfwGetDesktopMode(&desktopMode);
desktopHeight = desktopMode.Height;
desktopWidth = desktopMode.Width;


// --8<--

// On input handling, check if F11 is down.
if ( glfwGetKey( GLFW_KEY_F11 ) ) {
// Toggle fullscreen flag.
fullscreen = !fullscreen;

if ( fullscreen ) {
// Set window size for "fullscreen windowed" mode to the desktop resolution.
glfwSetWindowSize(desktopWidth, desktopHeight);

// Move window to the upper left corner.
glfwSetWindowPos(0, 0);
} else {
// Use start-up values for "windowed" mode.
glfwSetWindowSize(originalWidth, originalHeight);
glfwSetWindowPos(originalPosX, originalPosY);
}
}

ai - How can City-sim simulate hundreds of characters?


My games usually start lagging quite easily when there are a couple hundred of boxes representing possible characters. While games like SimCity or even Anno have hundreds of characters.


I realized that those games don't update everything at every tic, the needs are handled in intervals and it's not a render problem, but all of those tiny creatures have individual path-finding etc.
I simply can't understand how they can pull that off for thousands of characters even on old machines. How do they do this?


This question was updated to refer to huge Numbers where individuals don't really count and are simply simulated for immersion and aesthetics.


(Related if referring to individual characters: How does Dwarf Fortress keep track of so many entities without losing performance?)


(Different question but maybe related?: Rendering hundreds of animated characters in Unity3D)





Sunday, July 30, 2017

word usage - To live in village or on country?


Speaking about someone from a rural area, should we rather say "he's living in village" or "he's living on country"?


Country as a word has other meanings, such as the entity including the whole territory, so I'm cautious when this word is concerned. But that's only my feeling, and I'm not a native speaker.



Answer



Where I'm from, in the central U.S....




He lives in the country.



This means he lives outside of all city limits. His nearest neighbor is possibly a mile away.



He lives in a village.



This would be unusual in the U.S., where the word "village" is rarely used. You might get some funny looks, but would probably be understood to mean he lives in a small town; or perhaps in an old/Victorian neighborhood of a larger city.



He lives on the outskirts.




This would mean he lives in, or very near the city, but near the city's edge. He will have neighbors, and there will be a few stores near by, but it's not a particularly urban area.



He lives in the suburbs.



Similar to outskirts; perhaps slightly more urban connotations.


difference - Modals and Verbs for obligations and advice


must, should, need, have to, and have got to


Are all these sentences correct to say?





  • We must work to earn money.




  • We should work to earn money.




  • We need to work to earn money.




  • We have to work to earn money.





  • We have got to work to earn money.






Meaning of "clench" in "clenching the muscles in his forearms."


This is a passage from a novel:




Neal had both hands on the counter, clenching the muscles in his forearms. Like he was retroactively bracing himself for bad news. His head was hanging down, and his hair fell away from his forehead.



From OALD, clench is defined as:



when you clench your hands, teeth, etc., or when they clench, you press or squeeze them together tightly, usually showing that you are angry, determined or upset



From the definition, I understand what it means when you clench your teeth, but I don't understand what clenching mean in this passage when she said clenching the muscles in his forearms.




Tile sizes in 2D games



While developing a small game using tile-mapping method a question came to my mind:



I would develop the game on Windows but wouldn't exclude adapting it to another platform.


What size(in pixels) would you recommend using for creating the tiles of a tile-mapped game(ie: RPG) with the following requirements?



  • Have an acceptable level of detail without having too many tiles.

  • Having a decent map size.

  • Allow adaptation of the game on a handheld(ie: PSP), smartphone or a computer without too much loss of detail or slowdowns.

  • Allow more or less important zoom-in / zoom-out.

  • Have a resolution of tile that permits either pixel-perfect collision or block-collision.


Anything from a good explanation to a game example is useful as long as it can fit the requirements.



This question may seem a bit simplistic, but I noticed that many Indies game developer were using inappropriate scales scenery.


Also sorry for the poor syntax and the lack of vocabulary of my question, being a non-native English speaker doesn't help when talking about computers programming.



Answer



You can calculate the tile size based on the screen resolution and the number of tiles that need to be visible. If you were putting up a chess board (8x8 tiles) on a 768 pixel tall screen, your tiles can't be more than 768/8 or 96 pixels, otherwise they won't all fit on the screen. How many tiles need to be visible is of course dependent on your game design.


So decide how many tiles a player should see at once, decide on the screen resolution, and calculate from there.


That said, I like 64x64 ;^)




I wanted to go back and edit this old answer to add a link to a nice post with tile making guidelines. It could be of use to anyone looking at tile size and tile design in general.


http://lpc.opengameart.org/static/lpc-style-guide/styleguide.html This is a great


Saturday, July 29, 2017

path finding - How can I implement platformer pathfinding?


I've gone through A* pathfinding but could find anything on this. What I'm looking for is pathfinding for something kind of like a super smash bros level with different platforms. Can anyone point me in the right direction?



Answer



This entirely depends on the nature of the game's platforms. Can you jump through them from below? Can you drop down through them while standing? Can you pass through them while falling without landing? Can an NPC jump/glide/accelerate in a specific direction mid-air?


These are all questions you should be asking when implementing your pathfinding algorithm.


All in all, A* is pretty much applicable to all pathfinding. It's a very, very abstract algorithm, and all it requires is some sort of system of points or nodes in one form or another (polygonal vertices/edges/faces all work great for representing these) with some way to determine the "cost" of moving from one node to the next.


Given that the platforms will likely be flat surfaces, with no third dimension of movement, you could easily use a system of points that define the borders of each platform (left and right), and treat everything between those points as "walkable." From there, you just need to get your NPC to the goal location (which is decided by the AI behavior more than the pathfinding algorithm).



If you want to define AI behavior to be, say, "melee" aggressive, you'll likely want them to get as close to the player (or enemy, if the NPC is friendly) as possible, so they can attack them.


If you want to define AI behavior to be "ranged," you will likely want to find a position where the NPC is "safe" (distanced) but has a clear shot at the target.


The most efficient way for an NPC to detect these sorts of "hot spots" for target finding would be to pre-program them into the node map, itself.


For example, many NPCs in modern games know how to take cover behind obstacles, in combat. This is generally not because the AI is taught how to detect if an obstacle has a large enough bounding box to be used as cover, but rather because there is a pre-defined node (or, in fancier implementations, a polygon covering an area that is "acceptable to take cover at") told them that they should go there, and they likely detected that the player had too clear a shot at them (either by raycasting to the player's line of sight, or by the player's relative position with respect to the current position of the NPC).


AI behavior is full of quick little hacks like this that can all combine to make a fully functional, believable NPC.


sentence construction - Difference in meaning between 'I'd be surprised if he hadn't/hasn't'




"Has he tried to flirt with you yet? I'd be surprised if he hadn't."


"Has he tried to flirt with you yet? I'd be surprised if he hasn't."



Is the first one more appropriate than the second? And in both the sentences, I'm talking about present time.


Is there a difference between the two sentences?



Answer



Since you are asking this in ELL, I assume you are looking for some rules, not just usage patterns of native speakers.


There are rules for forming conditional sentences known as "the three conditionals" (or sometimes four). You can find a god explanation of these rules here. They are usually taught in ESL classes as strict rules, although as you can see in this discussion, some native speakers claim they are useless and don't reflect natural use of language; and definitely some native speakers never heard of these "rules".


There is merit in rules: If you follow them, you are practically assured to be well-understood and considered correct in formal writing or speech. Assuming that's what you are looking for, let's examine your sentences...



To clarify the difference, I'll change the sentences from interrogative to plain conditional declaratives (taking the tense from the second part):




  1. If he hadn't tried to flirt with you yet, I'd be surprised.

  2. If he hasn't tried to flirt with you yet, I'd be surprised.



The first sentence is exactly in the third conditional form, which discusses unreal past. It implies that (the speaker believes) "he has tried to flirt with you" but is thinking of "what if he hasn't?". So I'd say the corresponding sentence is perfectly fine:



Has he tried to flirt with you yet? I'd be surprised if he hadn't. (OK)




The second sentence does not fit any of the conditional forms - it uses present perfect instead of past perfect - so it may be considered ungrammatical... however, the original sentence uses present perfect (correctly) in its first part (the question), it may be more natural to keep the tense when referring to the same idea in its second part. I think it would be more common in practice...



Has he tried to flirt with you yet? I'd be surprised if he hasn't. (Also good)



In summary, both will be understood with the same meaning and you are unlikely to be "corrected" either way.


tense - She is/was going to the cinema



Incident which happened a week ago:



Me to Kate: "Where are you going"?
Kate: "I'm going to the cinema".




Now today I happen to tell this story to Jim and I say,



"I met Kate a week ago."
Jim: What did she say?
Me: "Kate said that she 'is' going to the cinema".



My question is, is the usage of 'is' grammatically correct? Here, at the time of reporting after a week I don't know if she's still going to the cinema or not and even then I use 'is' will this be grammatically correct?




Friday, July 28, 2017

do we use definite article before color or not?


Do we use definite article before colors?



This command gives me all the clickable content in the red color.





Answer



It depends on the context.


If the available colors are known, then we would say the red color.


If specific colors haven't yet been mentioned, or if a great many colors are available, then we would say red. You don't need "color".


By the way, we call it the definite article.


coordination - Subjective or Objective pronoun in this case?


I have recently been considering the correct use of "I" and "Me" in this particular case; Someone posted a picture of themselves, standing next to a celebrity, on a social media site, with the caption "[Celebrity name] and I". As the poster is a friend I was about to correct this to "[Celebrity name] and Me", but the more I thought about it the less certain I became.



I am usually good with "I" and "Me" and I understand how to use the handy rule of thumb to remove the "other person" to see if the sentence still makes sense. But in this case, there isn't much of a sentence to remove. However removing the reference to the other person would leave the caption as "I", which seems wholly wrong to me. But then I remembered that there is a style of speech where a person can refer to themselves this way- "'Tis I Sir!"...


So realising I needed to understand more about the use of the personal pronoun, and having no prior education is the finer detail of the English language from a grammatical rules perspective (that I can remember!) I went looking.


I found out about the Subjective and Objective case that defines this use and tried to apply that knowledge to the problem. However given the original caption I couldn't figure out whether the personal pronoun is the subject or object. I imagined the caption expanded into two sentences:



  • "This is a picture of [Celebrity name] and me"

  • "[Celebrity name] and I are in this picture"


How should I correctly parse "[Celebrity name] and I" to determine whether the personal pronoun is the subject or object, and whether, strictly speaking, "I" is allowed due to the older speech style or not?


Use of "I" here seems like a hypercorrection to me, but am I right or am I missing some subtle rule given the brevity of the sentence?



Answer




When looking at a photo, we usually point to ourselves and say



This is me.



So it's natural to take the the caption as Celebrity Name and me.


Thus, with This is me we have me being used in the so-called nominative case. Another example is the answer It's me to the question Who is it?


See the Merriam Webster video 'It is I' vs 'It's me'? and ELU's Which one is correct to say: "It's me" or "It's I"?.


See also this great answer by nohat on ELU about the specific use you are talking about: using me in such conjoined phrases as Celebrity Name and me, including subject phrases.


Forget about trying to pin English down to some rule that says speakers must always use I for the nominative and me for the objective. This is imposing the Latin case system on modern English, and it does not correctly describe the grammar of today's English.


This is me and It's me are grammatical in today's English. People who say it must be It's I are demanding that English speakers use rules for an entirely different language (Latin). That's weird, but unfortunately a couple hundred years ago a bunch of grammarians started doing this.



Thursday, July 27, 2017

prepositions - a specific usage of "of"


Could you think of any synonym phrase or words, so that they would be synonym with the following?



That idiot of a doctor


The real palace of a house



Thanks in advance




word form - Is "indices" or "indexes" the plural of "index"?


I've heard both plural forms of index, indices and indexes. I usually use indices when referring to the computer science term for database index, but I'm not sure if it is correct in that context.


Are both indices and indexes correct? If only one of them is correct, which one?



Answer



Both are correct, though there are some specific usages as pointed in another answer; Google Ngrams suggests that indices is slightly more used than indexes.



For American English we have (in both charts, indices is blue and indexes is red):


enter image description here


For British English we have:


enter image description here


word usage - "Both" vs "both of them"


What is the correct form in the following sentences, "both" and "both of them"?




a) "Both of them are unique."


b) "Both are unique."



If "both" by itself already contains "both of them", so I can conclude that the first option is not correct. Isn't it?




Wednesday, July 26, 2017

pronouns - Is referring to people as "it" considered rude?


In Japanese, referring to people as "it" considered rude. Instead of "it", We say "that person" or information of the person (ex. a person who wares a blue shirt).


In English, Is referring to people as "it" considered rude?



Answer



English doesn't have the same kind of strictures regarding how to reference people as Japanese does. We don't, out of politeness, refer to people as "that side" or "next door" (the way my Japanese in-laws do), but we definitely don't refer to people as it unless we are being extremely rude or condescending. Even then, this is something that would be said only in the heat of anger, and would be hard to take back.


Even babies are called he or she if the gender is known.


At all costs, avoid referring to someone as it.


Transform 3d viewport vector to 2d vector


I am playing around with 3d transformations and came along an issue.


I have a 3d vector already within the viewport and need to transform it to a 2d vector. (let's say my screen is 10x10)


Does that just straight works like regualar transformation or is something different here?


i.e.: I have the vector a = (2, 1, 0) within the viewport and want the 2d vector.


Does that works like this and if yes how do I handle the "0" within the 3rd component?



Answer



If you have a point in 3D space you can multiply it by the view and then projection matrix to get the screen coordinate. This is a preferable method since it allows for different screens and view parameters. The example in the link x = x / z won't usually work since it relies on a very specific view frustum. It might be a good approximation for some system.



The issue with just multiplying with the view and then projection matrix is that you can loose magnitude in your vector which might not be what you want. This is because the camera isn't necessarily centered on the world origin.


So a point in 3D space of (10, 10, 0) might come out in screen space as (5, 5) instead of the expected (10, 10) because of the camera position. Since it's just a point we want then it's fine, but if you were working out how a vector for velocity will impact a 2D object, then this is obviously bad.


Finally, transforming from a 3D to a 2D coordinate system isn't the same as translating from world space to screen space which seems to be what you are asking. Going from world to screen requires knowledge of the view eye (camera) and the screen. Going from 3D to 2D is a different transformation which involves calculating an objects projection onto a plane. (I think an orthographic projection matrix might give an easy way to do this though, as I can't remember how you actually do it).


hiring - Where to hire 2D sprite artists?



I'm looking for high quality original 2D sprite collections which are animated where appropriate. (IE not simply collections I can buy, we want original work).


I've had a look online but am struggling to find out where I can hire such people!



  • Where do I find such people?

  • How much should I expect to pay?




directx - Why are points adjusted using the projection and inverse view matrix during picking?


I am working on my first 3D game, which contains several vehicles placed on a board. I want to implement mouse picking of the vehicles. I found this great tutorial and used its code. But I don't understand part of the math.


Early in the function (listed below), I convert the input mouse coordinates into the -1 to +1 range:


// Create picking ray from camera position and mouse click

void VehiclePicker::SetPickingRay(LONG mouseX, LONG mouseY) {
float pointX, pointY;

/* Conversion to -1 to +1 here: */
// Move the mouse cursor coordinates into the -1 to +1 range.
pointX = ((2.0f * static_cast(mouseX)) / static_cast(SCREEN_WIDTH)) - 1.0f;
pointY = (((2.0f * static_cast(mouseY)) / static_cast(SCREEN_HEIGHT)) - 1.0f) * -1.0f;

...


Next, I adjust the points using the projection matrix. Listed below:


    XMFLOAT4X4 prMtrx;
// Convert projectionMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
XMStoreFloat4x4(&prMtrx, _d3d->GetProjectionMatrix());
pointX = pointX / prMtrx._11;
pointY = pointY / prMtrx._22;

I don't understand what is exactly done here. I understand that I should somehow transform the points using the inverted projection matrix into world space. But in the tutorial they are using non-inverted projection matrix and using only two elements from it for dividing the points. Why? In tutorial, they say they want "Adjust the points using the projection matrix to account for the aspect ratio of the viewport." Could somebody please explain it?


The same question is for the next part of the code. In tutorial they say "Calculate the direction of the picking ray in view space." Could you please also explain this one?


    // Get the inverse of the view matrix.

XMFLOAT4X4 invViewMtrx;
// Convert inverseViewMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
XMStoreFloat4x4(&invViewMtrx, XMMatrixInverse(nullptr, _camera->GetViewMatrix()));
XMFLOAT3 dir;
dir.x = (pointX * invViewMtrx._11) + (pointY * invViewMtrx._21) + invViewMtrx._31;
dir.y = (pointX * invViewMtrx._12) + (pointY * invViewMtrx._22) + invViewMtrx._32;
dir.z = (pointX * invViewMtrx._13) + (pointY * invViewMtrx._23) + invViewMtrx._33;
_pickingRayDirection = XMLoadFloat3(&dir);

I understand that the goal is to invert the process of rendering 3D scene into 2D screen. But I don't understand the math used.



Here's the rest of the function, for context:


    // Get the origin of the picking ray which is the position of the camera.
_pickingRayOrigin = _camera->GetPosition();

// And finally I must normalize the final vector
_pickingRayDirection = XMVector3Normalize(_pickingRayDirection);
}


Tuesday, July 25, 2017

sdl - SDL2 with OpenGL -- weird results, what's wrong?



I'm porting an app to iOS, and therefore need to upgrade it to SDL2 from SDL1.2 (so far I'm testing it as an on OS X desktop app only). However, when running the code with SDL2, I'm getting weird results as shown on the second image below (the first image is how it looks with SDL, correctly). The single changeset that causes this is this one, do you see something obviously wrong there, or does SDL2 have some OpenGL nuances I'm unaware of? My SDL is based on the latest from HG.


Update: another question about the iOS port of the same project is here.


Update 2: this is now also on the SDL newsgroup: http://thread.gmane.org/gmane.comp.lib.sdl/58026


Update 3: I tried using Regal for portable OpenGL, the not-so-good result is on the third screenshot, produced merely by replacing


#include 
#include

with


#include "GL/Regal.h"
#include "GL/RegalGLU.h"


using SDL 1.2 using SDL 2 using Regal with SDL 2



Answer



Heres your problem notice I comment out the surface = SDL_Get... it was giving some weird results. Also you forgot to create the OpenGL context. Let me know if you have any other issues.


SDLWindow::SDLWindow(int width, int height, double axisLen, const std::string &caption)
:m_fov(axisLen)
,m_width(0)
,m_height(0)
,m_fps(0)
,m_idxSnapshot(0)

,m_camPos(0, 0, 2)
,m_camLookAt(0, 0, 0)
,m_camOrient(0, 1, 0)
,surface(NULL)
,m_texStar(0)
,m_bRunning(true)
{
SDL_GLContext ctx;

if (SDL_Init(SDL_INIT_VIDEO) < 0)

throw std::runtime_error(SDL_GetError());
atexit(SDL_Quit);

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 0 );
SDL_GL_SetAttribute( SDL_GL_RETAINED_BACKING, 1 );

if ((window = SDL_CreateWindow(caption.c_str(), SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
SDL_WINDOW_BORDERLESS)) == NULL)

throw std::runtime_error(SDL_GetError());

/*if ((surface = SDL_GetWindowSurface(window)) == NULL)
throw std::runtime_error(SDL_GetError());*/

m_width = width;
m_height = height;

ctx = SDL_GL_CreateContext(window);


InitGL();
}

2d - Arc'd jumping method?


Okay, so I'm making a platformer, and I wanna know how I can make a arc'd jump easily. Like what Mario does in super Mario Bros 1. Any ideas on a simple way to accomplish this?




modal verbs - when to use "will" and "may" in a sentence.


Should I use "will" or "may" in the following sentence:




I'm not planning on leaving the country any time soon, but you just don't know when a passport may/will come in handy"?



One issue raised about the sentence was the usage of "may". Some people suggest I replace it with "will". I was wondering if the present construction is acceptable.




c++ - How do i implement a hit box system in a fighting game?



In a fighting game a move that you execute is basically just a series of hit boxes that are enabled and disabled at certain times. I want to know how do you create this hit box system. I have no idea as to how to make a flexible system where I can enable and disable a hit box on any frame of a move and also adding additional frame data. All I can think of is having a list that is the size of the amount of frames of the move, and add all of the enables, disables, and frame data as one list item. The problem with that is that a list item can only be one object so I have to somehow make all my frame data and hit box enables & disables into one object. If I can have as many hit boxes in a move as I want then this list item object needs to have a list as well, which I don't think is a good way of doing it. So I just want to know all of the good ways of implementing a hit box system in a fighting game.




unity - How to get the closest "visible" object from my "player"?


I'm using Unity 3d and i have to accomplish the following task: get the closest "visible" object to my player in forward direction.



It is a sort of radar.


I don't know where to start. Any advice is welcomed.


Thanks



Answer



Assuming that you're making a 3D game, you can use Physics.OverlapSphere to get a an array of Colliders that are within a certain range of the player. To check if the object is "visible" to the player, you could simply call Physics.Raycast in the direction of the object(s) returned by OverlapSphere and check if nothing that isn't the object you're checking for blocks the raycast. Here's a code example:


public class RadarController : MonoBehaviour
{
public int RadarRadius;
public string DetectableObjectTag;


public void CheckForVisibleObjects()
{
Collider[] objectColliders = Physics.SphereOverlap(this.transform.position, this.RadarRadius);
for(int index = 0; index <= objectColliders.Length - 1; index++)
{
GameObject colliderObject = objectColliders[index].gameObject;
if(colliderObject.tag == this.DetectableObjectTag)
{
RaycastHit hit;
bool hitOccurred = Physics.Raycast(this.transform.position, colliderObject.transform.position.normalized, out hit);

if(hitOccurred && hit.gameObject.tag == this.DetectableObjectTag)
{
// Do whatever you need to do with the resulting information
// here if the condition succeeds.
}
}
}
}

public void Update()

{
this.CheckForVisibleObjects();
}
}

Disclaimer: I am not able to check and see if this code works properly, or if it performs at an ideal rate. If there is an issue, just mention it and I'll see what I can do.


Monday, July 24, 2017

meaning in context - "written assignment" vs "writing assignment"


What's the difference between "written assignment" and "writing assignment"?


I was told just now this:



"...written assignment (is) versus oral assignment, and writing assignment (is) versus reading assignment..."



Does that mean that the difference is not in the definition (both are acts of writing something), but rather in the usage (that is, if the context is oral communication, then it's better to say "written assignment"; and if the context is reading, then it's better to say "writing assignment")?



Answer




You really need clarification from the one who assigned the work.


Unfortunately, the "assignment" can mean both the "details of the work to be done" and the "work that has been done", leaving room for confusion.


A writing assignment is easily understood as a request for the action of writing (example: write a paragraph).


A reading assignment is easily understood as a request for the action of reading (example: read this paragraph).


A written assignment can be understood in two ways: first, as a written request for some action (example: a note to get groceries); and second, as a written result or execution of a request (example: a written paragraph summarizing a story).


An oral assignment can be understood in two ways; first, as an oral request for some action (example: being told to get groceries); and second, as an oral result or execution of a request (example: reciting a poem).


xna - Orthographic Camera Zooming


In XNA I am using a spritebatch to render a board. I have created a camera class which can provide me a view and projection matrix. Currently I am supplying the view matrix to my sprite batch when I call begin.


I can get the view matrix to correctly move everything around and do some zooming in and out. My problem is that I want to zoom in on a specific point (for now the center of the screen) but currently zooming just zooms in on the coordinate 0,0.


Here is how I am constructing the view matrix;


        _ViewMatrix =
Matrix.CreateTranslation(

new Vector3(
(-_Position.X + _Width * _Zoom / 2),
(-_Position.Y + _Height * _Zoom / 2),
0) ) *
Matrix.CreateScale(new Vector3(_Zoom, _Zoom, 1));

How could this be altered to make it scale correctly relative to the given point. Later I will probably want to zoom to the mouse position, but if someone has a simple example I'm sure I can work out how to adapt it.



Answer



The following code creates the desired result.


        _ViewMatrix =

Matrix.CreateTranslation(-Position.X, -Position.Y, 0) *
Matrix.CreateScale(_Zoom, _Zoom, 1.0f) *
Matrix.CreateTranslation(_Width / 2, _Height / 2, 0.0f);

This will cause the camera to zoom into the center of the screen instead of the top left corner.


My understanding is that this code moves the camera such that the object I want to focus on, which is at (Position.X, Position.Y), is in the top left corner (0,0), then I'm scaling by the zoom factor and then finally moving the camera by half width/height so the top left corner is now in the center.


The code in the question would move the object to the center of the camera, but scaling is always in relation to the origin which would therefore move the point further away from 0,0 and thus it isn't at the center any more.


Since and the perfect tense


I know that saying:


(A) I am here since six o’clock. or (B) I was here since six o’clock.


would sound unidiomatic because of using "since" and its requisite tense which is present perfect. For example:


(C) - I have been here since six o’clock.


But I came across another sentence somewhere in a textbook which caused me to doubt. Is it possible to say:



(D) - I had been there since six o’clock.


If yes, what's the semantic difference between "C" and "D", and when should I use each one?



Answer



Your (D) is past perfect ... it refers to a time in the past just as (C) refers to a time in the present.


So (D) means that you were “there” from six o’clock to whatever past time you are talking about.



When Amy finally arrived at the bar at eight o’clock I had been there since six o’clock.



Projectile Motion - Arrow


In a 2D game, I simply want to draw the trajectory of an arrow in flight. With the code below, the trajectory (the parabola) looks right, but the angle (or rotation) or the arrow isn't.


float g = -9.8f;
float x = (launchVelocity * time);
float y = (launchVelocity * time) + (0.5f * g * (float)Math.Pow(time, 2));
float angle = (float)Math.Tanh(y / x);

What am I missing? Thanks.




passive voice - he was seen *to break* the window


We have a situation: someone saw the boy break the window. Can I make this passive sentence?




The boy was seen to break the window.



I use Murphy's Grammar and this structure is never discussed.



Answer




"The boy was seen breaking the window"



... as snailboat recommended is more common, but not more correct. I believe "the boy was seen to break the window" would be grammatically correct.


Consider what happens if you swap "seen" with "known": "The boy was known to break the window." No problem there - that's a common way to say it.


That said, I would still prefer "breaking" over "to break". "The boy was seen breaking the window. He was known to break windows frequently."



tense - Could have vs would have


could have vs would have


I know could means indicating a possibility or ability, and would means the past of will or something about that is uncertain.



Which of the following is correct?



If you had told me, I would have used the other route.
If you had told me, I could have used the other route.



Both of the above sound correct and similar to me.


Are these also possible?



If you had told me, I would use the other route.
If you tell me, I would use the other route.




Please clear my confusion.



Answer




If you had told me, I would have used the other route.
If you had told me, I could have used the other route.



Would here denotes a certain consequence of the unreal condition: no question about it, I would have used the other route.


Could denotes a possible consequence of the unreal condition: if you had told me, I might still have taken this route but I would have had the choice of taking the other route.




If you had toldPast Irrealis me, I wouldPresent Irrealis use the other route.
If you tellPresent Realis me, I wouldPresent Irrealis use the other route.



These are not quite impossible, but the circumstances under which either would be acceptable are very unlikely to arise. Ordinarily these forms would be understood as having the tense/mode significances I have noted in superscript, and in most cases the two verbs, the one in the IF clause and the one in the THEN clause, should have the same tense and mode.




This is not always the case in conditional clauses involving logical inference; but I do not think either of these sentences can be read as inferential.


licensing - Alternatives to remove Unity splash screen after developing a game with the free version?



I developed a simple game using the free version of Unity. I want to understand how much it would cost me to remove the Unity Splash Screen to know if it's worth it.


Right now Unity professional edition costs $75 per month, does this mean I have to pay every month while the game is on the app store or can I pay just for the month I have to release the game so I remove the Unity Splash Screen and that's all (provided I don't need to update the game later)?



Answer



According to the Unity store page, the $75/month subscription is locked in for 12 months, so it would cost $900 for one year. (click the $75/month price link for subscription details)


If you wanted to update your game after one year, you would need another subscription after that, so maybe $1,800 all up if you plan on updating your game after a year.


Or, you could pay the full one-off $1,500 price and have Unity 5 Pro be yours forever.




Edit: according to the Unity FAQ:



Do I need iOS + Android Pro in order to build to iOS + Android devices?



Unity Personal Edition includes deployment to Android and iOS with the Personal Edition splash screen. To deploy to iOS and Android without the Personal Edition Splash Screen you must purchase Unity Professional Edition together with iOS Pro and/or Android Pro deployment add-ons.



So it sounds like you would also need another $75/month or one-off $1,500 cost for the iOS Pro Add-on on top of Unity Pro.


So all up, you'd have to either pay for subscriptions for one year for both Unity Pro and iOS Pro for a total of $1,800 (assuming you weren't ever going to update your app after one year), or pay $3,000 for both as a one-off.


java - Why is there a huge update-delay in my client/server code?


I'm working on my Java game with Libgdx and having trouble with the network code. I can create a server, make multiple clients connect to it, but there is a huge delay between the player's input and the movement.


This is basically how it should work:




  1. SERVER: (Launch and listen to connection.)

  2. CLIENT: I want to connect

  3. SERVER: OK, here is the map and all other data

  4. CLIENT: I pressed "D"

  5. SERVER: OK, I move this player, here is your position

  6. CLIENT: I received my position


On the 2 last steps, when I pressed an input, the server gets it correctly and updates the position and immediately sends the position to the player, but here is my problem:


Server log (the numbers are X- and Y-coordinates):



Sat Sep 20 18:49:16 CEST 2014 : Send 2356.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2358.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2360.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2362.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2364.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Send 2366.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2368.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2370.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2372.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2374.0 1376.0

Sat Sep 20 18:49:17 CEST 2014 : Send 2376.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2378.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Send 2380.0 1376.0

Client log:


Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0 
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0

Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:16 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0
Sat Sep 20 18:49:17 CEST 2014 : Receive : 2336.0 1376.0

As you can see, the player receives the data at the wrong moment. Here is when the client start to receive



Sat Sep 20 18:49:18 CEST 2014 : Receive : 2336.0 1376.0 
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2338.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2340.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2342.0 1376.0
Sat Sep 20 18:49:18 CEST 2014 : Receive : 2344.0 1376.0

As you can see, there is almost a 2 seconds of delay (something like 1.6 / 1.7s).


This is how I send/receive data:


Sending:


synchronized(this.gestionPlayers) {

for(GestionPlayer gp : this.gestionPlayers) {
if(this.serializablePlayer.size() > 0)
gp.sendPlayer(this.serializablePlayer);
}
}

sendPlayer function:


try {
this.objectOut.writeObject(sp);
this.objectOut.reset();

} catch (IOException e) {
this.actif = false;
e.printStackTrace();
}

Receiving:


Vector p =
(Vector) this.objIn.readObject();
this.map.addNewPlayers(p);
this.map.multiplayerRender();


SerializablePlayer contains the player's ID and coordinates.


If you need more information, just ask. This is the last step in my multiplayer game and I'd be happy if you could help me! :)




animation - How to change/modify or animate an existing OpenGL object on Android?


I maybe know understand it all a little bit better so i thoug i make a new shorter question to eventually get an answer.


Get back or delete an existing OpenGL object, then change it and draw at new. How?



So if and Admin reads this post, he can feel free to delete it.


I'm working on OpenGL since a Week, so i'm new to the most stuff. (also my englisch isn't the best. Hop you can understand the most anyway)


So i'm working on an Tamagotchi App for a school project and want to make it with OpenGL. I allready came this far:


enter image description here


But now i want to animate things. My mind told me that it shoud be possible to change or modify an existing OpenGL object. In my situation there are 3 opjekts:



  1. Body

  2. Eyes

  3. Mouth



For example her is my code from the mouth:


public class GLMouth {

private int points = 1000;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;
private FloatBuffer vertBuff2;

public GLMouth(){


vertices = new float[points * 2];
for(int i=0; i<= (points+3); i+=3)
{
double rad = (Math.PI *i) / points;

vertices[i]=(float)Math.cos(rad);
vertices[i+1]=(float)Math.sin(rad);
vertices[i+2]=0;
}


ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
bBuff.order(ByteOrder.nativeOrder());
vertBuff=bBuff.asFloatBuffer();
vertBuff.put(vertices);
vertBuff.position(0);


vertices = new float[points * 2];
for(int i=0; i< (points+3); i+=3)
{

double rad = -(Math.PI *i) / points;

vertices[i]=(float)Math.cos(rad);
vertices[i+1]=(float)Math.sin(rad);
vertices[i+2]=0;
}

bBuff=ByteBuffer.allocateDirect(vertices.length*4);
bBuff.order(ByteOrder.nativeOrder());
vertBuff2=bBuff.asFloatBuffer();

vertBuff2.put(vertices);
vertBuff2.position(0);



}

public void draw(GL10 gl){

gl.glPushMatrix();

gl.glTranslatef(0.0f, -1.0f, 0.0f);
gl.glScalef(1.8f, 0.15f, 1.0f);
gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glPopMatrix();

gl.glPushMatrix();

gl.glTranslatef(0.0f, -1.0f, 0.0f);
gl.glScalef(1.8f, 1.0f, 1.0f);
gl.glColor4f(0.0f,0.0f,0.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff2);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glPopMatrix();

}


}

In my renderer i just creat a mouth object and then draw it with mouth.draw.


So i thought i have allready drawn the mouth and now i can cange for example the gl.glScalef(1.8f, 0.15f, 1.0f); from that existing mouth to zero with some time in between to let it look like the mouth is closing.


But how can i do that? I don't find anything with google, mostly because i don't know what i have to look up. If i understand OpenGL right, than it will just draw new mouths over the original.


edit Or it is a question about where is the opjekt? Can i save it an take it back (delete it etc) and draw it new with other properties.




c++ - Component-based design: handling objects interaction


I'm not sure how exactly objects do things to other objects in a component based design.


Say I have an Obj class. I do:


Obj obj;
obj.add(new Position());
obj.add(new Physics());

How could I then have another object not only move the ball but have those physics applied. I'm not looking for implementation details but rather abstractly how objects communicate. In an entity based design, you might just have:



obj1.emitForceOn(obj2,5.0,0.0,0.0);

Any article or explanation to get a better grasp on a component driven design and how to do basic things would be really helpful.



Answer



That is usually done using messages. You can find lots of details in other questions on this site, like here or there.


To answer your specific example, a way to go is to define a small Message class that your objects can process, e.g:


struct Message
{
Message(const Objt& sender, const std::string& msg)
: m_sender(&sender)

, m_msg(msg) {}
const Obj* m_sender;
std::string m_msg;
};

void Obj::Process(const Message& msg)
{
for (int i=0; i {
// let components do some stuff with msg

m_components[i].Process(msg);
}
}

This way you're not "polluting" you Obj class interface with component-related methods. Some components can choose to process the message, some might just ignore it.


You can start by calling this method directly from another object:


Message msg(obj1, "EmitForce(5.0,0.0,0.0)");
obj2.ProcessMessage(msg);

In this case, obj2's Physics will pick the message, and do whatever processing it needs to do. When done, it will either:




  • Send a "SetPosition" message to self, that the Position component will pick;

  • Or directly access the Position component for modifications (quite wrong for a pure component-based design, as you can't assume every object has a Position component, but the Position component could be a requirement of Physics).


It's generally a good idea to delay the actual processing of the message to the next component's update. Processing it immediately could mean sending messages to other components of other objects, so sending just one message could quickly mean an inextricable spaghetti stack.


You'll probably have to go for a more advanced system later on on: asynchronous message queues, sending messages to group of objects, per-component registering/unregistering from messages etc.


The Message class can be a generic container for a simple string as shown above, but processing strings at runtime isn't really efficient. You can go for a container of generic values: strings, integers, floats... With a name or better yet, an ID, to distinguish different types of messages. Or you can also derive a base class to fit specific needs. In your case, you could imagine an EmitForceMessage that derives from Message and adds the desired force vector -but beware of the runtime cost of RTTI if you do so.


java - How to make the background of an OpenGL object transparent?



It sounds so simple but i didn't get it to work.


The Background of my FrameLayout where i add the GLSurfaceView in is colored blue but there is only black.


So here is my method to initiate the Surface...GL..


private void initGL(){

ourSurfaceView = new GLSurfaceView(this); // GLSurfaceView Objekt erstellen

ourSurfaceView.setEGLConfigChooser(new MultisampleConfigChooser());
ourSurfaceView.setRenderer(new GLRendererTamago());

//In every help i read that it shoud help to use the following two commands... but they did nothing for me.
ourSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
ourSurfaceView.setZOrderOnTop(true);

FrameLayout tama_layout = (FrameLayout)findViewById(R.id.LayoutTama);
tama_layout.addView(ourSurfaceView, 0);


}

Someone have any idea?


edit: added the code from my renderer


@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {

gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_BLEND);

gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
// gl.glClearDepthf(1f);
// gl.glClearColor(0,0,0,0);
}

@Override
public void onDrawFrame(GL10 gl) {

gl.glDisable(GL10.GL_DITHER);

gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0, 0, -5, 0, 0, 0, 0, 2, 0);

body.draw(gl);
eyes.draw(gl);
mouth.draw(gl);
}


@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {

gl.glViewport(0, 0, width, height);
float ratio = (float)width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 20);
}


Sunday, July 23, 2017

appositives - Article usage in a noun clause: "Tim Courtney, (a?) (the?) chief investment officer of Exencial Wealth Advisors, said.."


I am struggling with using articles in noun clauses. I have seen some examples where an articles is omitted when the following noun is not even uncountable. For example:


"Tim Courtney, chief investment officer of Exencial Wealth Advisors, said: 'We're stockpiling commodities and demand is not picking up. It's kind of a depressing market.'"


Would it be correct if I write " Time Courtney, a chief investment officer of Exencial Wealth Advisors,..." with an article. I do not believe the word "officer" is uncountable.


Another example to further explain my problem: Mr. Smith, a teacher at Lincoln high school, has a phD degree in math. or Mr. Smith, teacher at Lincoln high school, has a phD degree in math.


Which one is grammatically correct? Or are both acceptable? or they simply carry different meanings.


Please help. Thank you.



Answer



Both are correct.



"Tim Courtney, chief investment officer of ... " sounds more authoritative, since we don't know whether he's the only chief investment officer, or one of the two chief investment officers, etc.


"Tim Courtney, a chief investment officer of ... " lets you know that he's one of many, which right away undermines his authority.


phrase request - How to translate "dropped my heart"?



There's a phrase in Thai, ตกใจหมดเลย [tòk-tɕɑi-mòt-lɤːi], which means "to be frightened", as if someone suddenly broke a glass on a floor behind your back.


Literally, it can be translated "dropped-heart-depleted-completely" (don't try Google Translate; it's wrong).


Surprisingly enough, I understood it intuitively because there's a Russian idiom "душа ушла в пятки" ("soul went to {one's} heels").
Both Thai and Russian idioms hold a certain amount of humorous context.


I was trying to translate it to English, but only found "frightened to death" which does not look humorous at all. Is there a better phrase to denote being frightened, with considerations above?



Answer



If you're looking for something humorous, then you'll have to create your own translation, in the spirit of Arthur Waley, the great American translator of poetry from Chinese and Japanese to English. Waley was criticized, unjustly, IMHO, for his brilliant translation of The Tale of Genji by a contemporary translator, Edward Seidensticker, touted as "the best translator of Japanese that has ever lived", but, frankly, I found his "faithful to the original text" translation an utter bore compared with Waley's. Waley was a poet; Seidensticker was a translator. There's a world of difference.


Enough background. I'm suggesting that you create your own phrase. I'm not a poet, but I do have a suggestion. Why not say something on the order of "my heart dropped down my leg and into my shoe, rolled between my toes, then stopped for a full five seconds until I caught my breath again"? You can change things to say what you think will amuse your readers or listeners. Everything else that's been suggested here, including my earlier suggestion of "my heart lept into my mouth", is merely a cliché. Avoid clichés whenever possible.


past participles - passive Gerunds to express likes or dislikes


I've read these sentences in my grammar book. And it says "we use I like ... and I don't like+gerund/noun". Example sentences are:




  1. I like being obeyed by my students.

  2. I don't like being laughed at.

  3. I don't like being asked irrelevant questions.




I don't understand it because we can also use the to-infinitive to express like or dislike, for example:



I like to be obeyed by my students.



So, why to use gerunds like above? Could you please tell me about the "being+past participle" form related to gerunds? Is it the passive of the -ing form? If so, how would the sentences look like in active form?


Source: http://www.learnamericanenglishonline.com/Green%20Level/G15%20Gerunds%20Passive.html




Reasons for these two past perfect tenses



I had once vowed that I would never call her aunt again: I thought it no sin to forget and break that vow now. My fingers had fastened on her hand which lay outside the sheet: had she pressed mine kindly, I should at that moment have experienced true pleasure. But unimpressionable natures are not so soon softened, nor are natural antipathies so readily eradicated. Mrs. Reed took her hand away, and, turning her face rather from me, she remarked that the night was warm. (Jane Eyre)



Are the two past perfect because of the past tenses below, or because of some other reasons?


(Past tense)--------------------(the past of the Past tense)
I thought it no sin-------------I had once vowed
Mrs. Reed took her hand away----My fingers had fastened


Answer



I think you've got it. The Reference time (narrative time) here is the sequence of moments marked with the past tense. The past perfects mark their events as occurring before the corresponding past moments:



                      NARRATIVE TIME
I had once vowed           before   I thought it no sin ... now
My fingers had fastened      before   [her hand] lay outside the sheet
[a counterfactual and
a general observation, and then]
       Mrs. Reed took her hand away, and ... remarked



Actually, her hand may be presumed to have lain outside the sheet before Jane took it ... but in the sentence what is relevant is that it lies there in Reference time.



Saturday, July 22, 2017

sentence construction - what does 'all the more significant for being so rare' mean?


Excerpted from the site sparknote:


Amidst the callousness and exploitation, moments of compassion are few and far between, although perhaps all the more significant for being so rare. Even though he is taken in only grudgingly, the old man eventually becomes part of Pelayo and Elisenda’s household. By the time the old man finally flies into the sunset, Elisenda, for all her fussing,


I couldn't make heads or tails of the bold part not only semantically also analyctically to analyse the part(grammatically).



Answer



Original text:



Amidst the callousness and exploitation, moments of compassion are few and far between, although perhaps all the more significant for being so rare.




In plain English:



Being surrounded by the emotionless and unfair treatment, moments of compassion are rare, but perhaps these moment are even more significant because they are very rare.





Let's take a closer look at the transformation of the part you ask about:



although [ perhaps ] [ all the more significant [ for being so rare ] ]
= but [ perhaps ] [ these moments are even more significant [ because they are very rare ] ]




Explanation:


although = but. In formal writing we can use although to introduce a reduced clause (a clause without a verb). The reduced part in this context is these moments.


all the more = even more.


for being: for in this context is used to mean because; for being so rare in this sentence means "because they (moments of compassion) are so rare".


adverbs - Difference between 'good' and 'well'


What can I say instead of "I'm very tired, I guess I'm sick"?





  1. I don't feel good.

  2. I don't feel well.

  3. I feel bad.

  4. I'm not good.

  5. I'm not well.




Answer



"Good" is an adjective meaning positive or desirable, as in "this is a good book", or morally upright, as in "Fred has never hurt anyone. He is a good man". Less often, "good" can be a noun meaning "benefit" or "well-being", as in, "We must all sacrifice for the good of the whole." "Well" can be an adverb meaning in a positive or desirable way, as in, "Since he took a class on public speaking, Fred talks well", or it can be an adjective meaning healthy, "After taking the medicine he felt well again".



English speakers, including native speakers, often confuse the adjective good with the adverb well. People will say, "She sings good", when what they mean is, "She sings well." If the idea is to describe the quality of her singing, then "sing" is a verb and so should be modified by an adverb such as "well", not by an adjective.



I don't feel good.



Valid. "Good" is a predicate adjective describing "I". You don't feel that you are in a desirable condition. In context, this sentence could also mean that you do not believe you are morally upright. "You are a very good person, Bob." "Well, I don't feel good. I think I have many ethical failings." But that's a rare usage.



I don't feel well.



Valid. "Well" is being used as an adjective describing "I". You don't feel healthy. Note this is a different and possibly confusing use of "well" then if you said, "I don't run well." In that case "well" is being used as an adverb modifying the verb "run", and so the meaning is, "My performance as a runner is not up to standard." (Conceivably, "I don't feel well" could mean that you are not good at feeling, like if you have nerve damage to your fingers, but that is a very unlikely meaning.)




I feel bad.



Pretty much the opposite of "I feel good." Usually people say this to mean that they are not feeling healthy or otherwise are not in good condition. It is also used to mean morally bad. People will sometimes say, "Oh, I feel bad tonight" meaning "I am prepared to engage in acts that some consider morally wrong but that I think will be fun."



I'm not good.



The most obvious meaning would be "I am not morally upright." As in, "Do you believe that you are a good person?" "No, I'm not good. I have done many evil things." In context it could also mean not capable or adept. Like, "We need another member for our baseball team. How are you at baseball?" "Oh, you don't want me. I'm not good."



I'm not well.




I am not healthy. "Well" here is being used as an adjective describing state of health.


xna - How do I autogenerate gradient lighting?


I am trying to think of a way to generate a gradient like this picture:


a radial gradient



Something like this GetGradientTexture(360f,100(width),100(height)), or if i want a directional light (like a flashlight) 180f,10,200.


But I can't really think of a good way to do this. Does anyone have anything that can push me in the right direction?




sentence construction - such..that / so.. that


Here's a sentence.



Feeling flushed is such a natural response to sudden self-consciousness that if it weren't part of an emotionally crippling experience, it could almost be overlooked.




and can I rewrite like the following?



Feeling flushed is so natural a response to sudden self-consciousness that if it weren't part of an emotionally crippling experience, it could almost be overlooked.




Answer



"So [adjective] a [noun]" is a valid, though perhaps slightly old-fashioned, pattern. So yes, that rephrasing works.


See Damkerng T's answer to a similar question with another citation.


Has Java 3D changed much since 2005?



I'm thinking of picking up the book called "Killer Game Programming" by Andrew Davidson, but its pretty old, now. I know Java, and I've been messing with jMonkeyEngine for a few days, but I'm curious to see if I would benefit from the 3D chapters of this book.


The book was published was in 2005. Has Java changed to the point where this book would now be obsolete, assuming it was up to date at time of publication?




How do I determine my games minimum hardware/software requirements?


With me going it alone in development I only have limited resources at my disposal i.e one pc with which I develop and test the game. so I only know for certain my game works with that setup.


What options have I got in testing the game on the many different hardware/operating system combinations? Its a windows desktop game.



Answer



Off the top of my head I'd suggest trying to run the game on a few other PCs from friends or relatives. After that you might want to consider some form of beta test, i.e. publishing a demo or something so you can get community feedback.


Thursday, July 20, 2017

c++ - Am I on the right track with this component architecture?


I've recently decided to revamp my game architecture to get rid of deep class hierarchies and replace them with configurable components. The first hierarchy I'm replacing is the Item hierarchy and I would like some advice to know if I'm on the right track.


Previously, I had a hierarchy that went something like this:


Item -> Equipment -> Weapon
-> Armor

-> Accessory
-> SyntehsisItem
-> BattleUseItem -> HealingItem
-> ThrowingItem -> ThrowsAsAttackItem

Needless to say it was starting to get messy and these was no easy solution to items that needed to be multiple types (i.e. some equipment is used in item synthesis, some equipment is throwable, etc.)


I then attempted to refactor and place functionality into the base item class. But then I was noting that the Item had alot of unused/superfluous data. Now I'm trying to do a component like architecture, at least for my items before attempting to do so to my other game classes.


Here's what I'm currently thinking for the component setup:


I have a base item class that has slots for various components (i.e. an equipment component slot, a healing component slot, etc. as well as a map for arbitrary components) so something like this:


class Item

{
//Basic item properties (name, ID, etc.) excluded
EquipmentComponent* equipmentComponent;
HealingComponent* healingComponent;
SynthesisComponent* synthesisComponent;
ThrowComponent* throwComponent;
boost::unordered_map > AdditionalComponents;
}

All item components would inherit from a base ItemComponent class, and each Component type is responsible for telling the engine how to implement that functionality. i.e. the HealingComponent tells the battle mechanics how to consume the item as a healing item, while the ThrowComponent tells the battle engine how to treat the item as a throwable item.



The map is used to store arbitrary components that are not core item components. I'm pairing it with a bool to indicate whether the Item Container should manage the ItemComponent or if it's being managed by an external source.


My idea here was that I define the core components used by my game engine up front, and my item factory would assign the components that the item actually has, otherwise they are null. The map would contain arbitrary components that would generally be added/consumed by scripting files.


My question is, is this a good design? If not, how can it be improved? I considered grouping all components into the map, but using string indexing seemed unecessary for the core item components



Answer



It seems like a very reasonable first step.


You're opting for a combination of generality (the "additional components" map) and lookup performance (the hard-coded members), which may be a bit of a pre-optimization -- your point concerning the general inefficiency of string-based look-up is well-made, but you can alleviate that by choosing to index components by something faster to hash. One approach might be to give each component type a unique type ID (essentially you're implementing lightweight custom RTTI) and index based on that.


Regardless, I would caution you to expose a public API for the Item object that allows you ask for any component -- the hardcoded ones and the additional ones -- in a uniform fashion. This would make it easier to change the underlying representation or balance of hardcoded/non-hardcoded components without having to refactor all the item component clients.


You might also consider providing "dummy" no-op versions of each of the hard-coded components and ensure that they are always assigned -- you can then use reference members instead of pointers, and you will never need to check for a NULL pointer before interacting with one of the hard-coded components classes. You will still incur the cost of the dynamic dispatch to interact with that component's members, but that would occur even with pointer members. This is more of a code cleanliness issue because the performance impact will be negligible in all likelihood.


I don't think it's a great idea to have two different kinds of lifetime scopes (in other words, I don't think the bool you have in the additional component map is a great idea). It complicates the system and implies that destruction and resource release isn't going to be terribly deterministic. The API to your components would be much clearer if you opted for one lifetime management strategy or the other -- either the entity manages the component lifetime, or the subsystem that realizes components does (I prefer the latter because it pairs better with the outboard component approach, which I will discuss next).


The big downside I see with your approach is that you are clumping all of the components together in the "entity" object, which actually isn't always the best design. From my related answer to another component-based question:




Your approach of a using a big map of components and an update() call in the game object is quite sub-optimal (and a common pitfall for those first building these sorts of systems). It makes for very poor cache coherency during the update and doesn't allow you to take advantage of concurrency and the trend towards SIMD-style process of large batches of data or behavior at once. It's often better to use a design where the game object doesn't update its components, but rather the subsystem responsible for the component itself updates them all at once.



You're essentially taking the same approach by storing the components in the item entity (which is, again, an entirely acceptable first step). What you may discover is that the bulk of the access to components you are concerned about the performance of is just to update those, and if you elect to use a more outboard approach to component organization, where the components are kept in a cache-coherent, efficient (for their domain) data structure by a subsystem that understands their needs the most, you can achieve much better, more parallelizable update performance.


But I point this out only as something to consider as a future direction -- you certainly don't want to go overboard overengineering this; you can make a gradual transition through constant refactoring or you may discover your current implementation meets your needs perfectly and there's no need to iterate on it.


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