Sunday, July 31, 2016

word choice - "What is the weather today?" or "How is the weather today?"


If I want to ask about the weather today whether is cold or hot, worm or cloudy or foggy, rainy or snowy etc. What should I choose of these two (or may be there's another way)?



"What's the weather today?"



or



"How's the weather today?"




What's the appropriate choice for the mentioned need?




Unity 5.1 Asset bundle for windows


I am working on the asset bundle method, i know how to use the asset bundle for untiy 4.x series but i am trying to do this in unity5. I heard in unity 5 is more compatibility to do. I searched in youtube and google but i didnt get the proper tutorial to how to use that. So please suggest me or provide some tutorial to do this.


Thanks in Advance.




beziers - Collision detection with curves


I'm working on a 2D game in which I would like to do collision detection between a moving circle and some kind of static curves (maybe Bezier curves).


Currently my game features only straight lines as the static geometry and I'm doing the collision detection by calculating the distance from the circle to the lines, and projecting the circle out of the line in case the distance is less than the circles radius.


How can I do this kind of collision detection in a relative straightforward way? I know for instance that Box2D features collision detection with Bezier curves. I don't need a full featured collision detection mechanism, just something that can do what I've described.




UPDATE: Thanks a lot for the great answers! I'll have to read up on Bezier curves to fully understand the method you've described. Then I'll get back to you.



Answer




29/09/2012 - 23:20


I created a git Repo here: https://github.com/ArthurWulfWhite/Bezier-Distance/


You are welcome to download the source files as a zip from there. It also includes a demo you can compile using FlashDevelop. To use the demo, open the project in Flash Develop and click 'Test Project'. While running the demo, click the LMB to randomize a new Bezier curve and a new Circle.


Good luck!


The zip link is hard to see - just use Ctrl + F and type zip. This source represents a couple of weeks of reasearch and programming, I hope you enjoy it.




If you plan on dividing the bezier recursively into segments and checking for collisions with them, I suggest making a 100,100 array (grid) and placing each segment in the four nearest squares, so you only have to check for collisions with 4 / 10,000 of the segments each frame.


I do think you will benefit from box2d both as a programmer and as a game creator, since there are lots of hidden little hurdles in making a 'simple' physics engine that make the motion seem a little bumpy and less fluid then it could be.


Old answer: The pure way.


You can actually see if a circle is colliding with a Bezier curve, by checking the distance between the distance between the center of the circle and the closest point on the curve.



The equation for the distance (in general)


explained:


Bezier equation:


q(t) = (1-t) * ((1-t) * start.(x,y) + t * control.(x,y)) + t*(t * control.(x,y) + (1 - t) * end.(x,y))

This can be summed up to (with some algebra) - I will omit .(x,y) for readability (they are still points, not one number)


q(t) = (start -2 * cont + end) t^2 + (-2 * start + 2 * control) + start

The distance from point (x,y) is:


sqrt ((q(t).x - point.x)^2 + (q(t).y - point.y)^2)


To find the closest point on the bezier to the ball, you need to derive and find all the points where the derivative equals zero (the roots). It is a polynomial of the third degree so you could use a closed formula but it could be unreliable since the precision of the computer floating point represented fractions may not be sufficient. It is far better to use Newton or something of that nature.


The derivative you need to find the roots for is:


Assuming: a = start b = control c = end d = cirlce center point


Derivative using wolfram alpha


The tricky part is multiplying this points, you have to use dot product.


If you like, I have the code for this and I can share it here in the form of a function that simply returns a boolean if there is a collision or not and an angle of collision. Some problems could appear in naive implementation of a collision engine like this for instance a fast moving ball could get caught between two curves.


I recommend avoiding it for now, just sum up the coefficients for the x axis and for the y axis and add them up.


The use any reliable method you may choose like Newton to find the roots, check the distance from the root points on the bezier, 0 <= t <= 1 to the circle center and check the distance for the two ends of the bezier (start and end) to the circle center, whichever one is closest, will tell you if there is a collision.


If the radius is smaller than the minimal distance, there is a collision.



The angle is approximately the one between the center of the circle and the closest point on the bezier.


That being said, if you truly wish to make a game with collision physics, I suggest you just iterate over the bezier


    q(t) = (1-t) * ((1-t) * start.(x,y) + t * control.(x,y)) + t*(t * control.(x,y) + (1 - t) * end.(x,y))

Divide each piece in the middle recursively until it is small enough, lets say 10 pixels or less, then build the bezier roughly from boxes and use Box2d for the physics cause it is possible that writing all this collision detection code will prove to be a great time sink that doesn't enhance the gameplay much. Using Box2d has proven itself in countless projects in the past.


past tense - I had done when you had come by the evening


We have "A" and B moments in the past. "A" happened first, "B" happened second. "A" should be in Perfect. Example:


I had done when you came


I had done - "A"


When you came - "B"


"A" happened before "B"


If now we have "B" and "C" where "B" happened before "C", then "B" should be in Perfect, "C" - in Past Simple(if it's a verb). Example:


You had come by the evening



You had come - "B"


By the evening - "C"


Now we have "A", "B" and "C". "A" should be in Perfect because it happened before "B" but "B" simultaneusly should be in Perfect, either, because it in its part happened before "C". It's like if we have "A" and "D" where "A" is just "A" but "D" is ["B"+"C"]. Example:


I had done when you had come by the evening


I had done - "A"


When you had come - "B"


By the evening - "C"


When you had come by the evening - "D" ["B"+"C"]


Congratulations? Well done? Can I be proud of myself?:D




Saturday, July 30, 2016

mathematics - Why do we use the Pythagorean theorem in game physics?


I've recently learned that we use Pythagorean theorem a lot in our physics calculations and I'm afraid I don't really get the point.


Here's an example from a book to make sure an object doesn't travel faster than a MAXIMUM_VELOCITY constant in the horizontal plane:


MAXIMUM_VELOCITY = ;
SQUARED_MAXIMUM_VELOCITY = MAXIMUM_VELOCITY * MAXIMUM_VELOCITY;

function animate(){

var squared_horizontal_velocity = (x_velocity * x_velocity) + (z_velocity * z_velocity);

if( squared_horizontal_velocity <= SQUARED_MAXIMUM_VELOCITY ){

scalar = squared_horizontal_velocity / SQUARED_MAXIMUM_VELOCITY;

x_velocity = x_velocity / scalar;
z_velocity = x_velocity / scalar;
}
}


Let's try this with some numbers:


An object is attempting to move 5 units in x and 5 units in z. It should only be able to move 5 units horizontally in total!


MAXIMUM_VELOCITY = 5;
SQUARED_MAXIMUM_VELOCITY = 5 * 5;
SQUARED_MAXIMUM_VELOCITY = 25;

function animate(){
var x_velocity = 5;
var z_velocity = 5;


var squared_horizontal_velocity = (x_velocity * x_velocity) + (z_velocity * z_velocity);
var squared_horizontal_velocity = 5 * 5 + 5 * 5;
var squared_horizontal_velocity = 25 + 25;
var squared_horizontal_velocity = 50;

// if( squared_horizontal_velocity <= SQUARED_MAXIMUM_VELOCITY ){
if( 50 <= 25 ){
scalar = squared_horizontal_velocity / SQUARED_MAXIMUM_VELOCITY;
scalar = 50 / 25;

scalar = 2.0;

x_velocity = x_velocity / scalar;
x_velocity = 5 / 2.0;
x_velocity = 2.5;

z_velocity = z_velocity / scalar;
z_velocity = 5 / 2.0;
z_velocity = 2.5;


// new_horizontal_velocity = x_velocity + z_velocity
// new_horizontal_velocity = 2.5 + 2.5
// new_horizontal_velocity = 5
}
}

Now this works well, but we can do the same thing without Pythagoras:


MAXIMUM_VELOCITY = 5;

function animate(){

var x_velocity = 5;
var z_velocity = 5;

var horizontal_velocity = x_velocity + z_velocity;
var horizontal_velocity = 5 + 5;
var horizontal_velocity = 10;

// if( horizontal_velocity >= MAXIMUM_VELOCITY ){
if( 10 >= 5 ){
scalar = horizontal_velocity / MAXIMUM_VELOCITY;

scalar = 10 / 5;
scalar = 2.0;

x_velocity = x_velocity / scalar;
x_velocity = 5 / 2.0;
x_velocity = 2.5;

z_velocity = z_velocity / scalar;
z_velocity = 5 / 2.0;
z_velocity = 2.5;


// new_horizontal_velocity = x_velocity + z_velocity
// new_horizontal_velocity = 2.5 + 2.5
// new_horizontal_velocity = 5
}
}

Benefits of doing it without Pythagoras:



  1. Less lines


  2. Within those lines, it's easier to read what's going on

  3. ...and it takes less time to compute, as there are less multiplications


Seems to me like computers and humans get a better deal without Pythagorean theorem! However, I'm sure I'm wrong as I've seen Pythagoras' theorem in a number of reputable places, so I'd like someone to explain me the benefit of using Pythagorean theorem to a maths newbie.


Does this have anything to do with unit vectors? To me a unit vector is when we normalize a vector and turn it into a fraction. We do this by dividing the vector by a larger constant. I'm not sure what constant it is. The total size of the graph? Anyway, because it's a fraction, I take it, a unit vector is basically a graph that can fit inside a 3D grid with the x-axis running from -1 to 1, z-axis running from -1 to 1, and the y-axis running from -1 to 1. That's literally everything I know about unit vectors... not much :P And I fail to see their usefulness.


Also, we're not really creating a unit vector in the above examples. Should I be determining the scalar like this:


// a mathematical work-around of my own invention. There may be a cleverer way to do this! I've also made up my own terms such as 'divisive_scalar' so don't bother googling
var divisive_scalar = (squared_horizontal_velocity / SQUARED_MAXIMUM_VELOCITY);
var divisive_scalar = ( 50 / 25 );
var divisive_scalar = 2;


var multiplicative_scalar = (divisive_scalar / (2*divisive_scalar));
var multiplicative_scalar = (2 / (2*2));
var multiplicative_scalar = (2 / 4);
var multiplicative_scalar = 0.5;

x_velocity = x_velocity * multiplicative_scalar
x_velocity = 5 * 0.5
x_velocity = 2.5


Again, I can't see why this is better, but it's more "unit-vector-y" because the multiplicative_scalar is a unit_vector? As you can see, I use words such as "unit-vector-y" so I'm really not a maths whiz! Also aware that unit vectors might have nothing to do with Pythagorean theorem so ignore all of this if I'm barking up the wrong tree.


I'm a very visual person (3D modeller and concept artist by trade!) and I find diagrams and graphs really, really helpful so as many as humanely possible please!



Answer



Your Pythagoras-free code doesn't compute a length as we normally think of it.


Normally in 3D games we model the world as a Euclidean space, and we use a Euclidean distance metric (also known as Pythagorean Theorem) to calculate the total length of a vector v with components v.x and v.y. Namely:


EuclideanLength(v) = sqrt(v.x * v.x + v.y * v.y)

(Note that this square root is missing in your sample code above, which is why the two approaches appear to give the same answer. More on that shortly...)


The code you've described uses the Manhattan distance metric:


ManhattanLength(v) = abs(v.x) + abs(v.y)


(Although you didn't include the absolute values, which may make it behave unexpectedly for negative numbers)


It's easy to see that these two distance functions match-up when v.x or v.y is zero, and we're only moving along one axis. How do they compare though when we move diagonally?


Let's say v.x = v.y = 1. How long is this vector (equivalently, how fast is the velocity it describes)?


Euclidean                              Manhattan

sqrt(v.x*v.x + v.y * v.y) abs(v.x) + abs(v.y)
sqrt(1 * 1 + 1 * 1) abs(1) + abs(1)
sqrt(2) 1 + 1
1.414... 2


You can see these metrics don't actually agree for diagonal lines.


Let's plot on a graph the set of points that each metric says are a distance of 1 away from the origin:


Distance metrics


Our familiar Euclidean metric is the red circle. This is the set of all points x,y such that x^2 + y^2 = 1. You can see that it's rotationally-symmetric, and that's why we like it: it neatly represents the idea that distance doesn't change with direction.


The Manhattan metric is the blue diamond. Not a great match for our intuitive idea of distance - but that doesn't make it bad. In many tile-based games where you move in discrete steps in the four cardinal directions, the Manhattan metric gives the correct distance between points (in terms of "how many moves will it take to get there?")


Finally, I threw in the Chebyshev metric for fun - it's the green square:


ChebyshevLength(v) = max(abs(v.x), abs(v.y))

It's also good for tile-based games, where you're allowed to move on diagonals. A King in Chess moves according to the Chebyshev metric.



I hope that clears up what the difference is between typical Pythagorean-style code and the example you provided above.


What is the meaning of little to bad?



I have come across many sentences involving phrases like "litte to bad", "little too comfortable", "I am little too busy". What exactly does it mean ?




OpenGL ES 2.0: Mixing 2D with 3D


Is it possible to mix 2D and 3D graphics in a single OpenGL ES 2.0 game, please?


I have plenty of 2D graphics in my game. The 2D graphics is represented by two triangular polygons (making up a rectangle) with texture on them. I use orthographic matrix to render the whole scene.


However, I need to add some 3D effects into my game. Threfore, I wish to use perspective camera to render the meshes.



Is it possible to mix orthographic and perspective camera in one scene? If yes, is there going to be a large performance cost for this? Is there any recommended approach to do this effectively? I wil have 90% of 2D graphics and only 10% of 3D.


Target platform is OpenGL ES 2.0 (iOS, Android). I use C++ to develop.


Thank you.



Answer



This is easily done.


Set the view transform to orthographic for the 2D stuff, and render it. Then, before clearing the framebuffer, draw the effects with a perspective projection. The projection will only effect the geometry drawn after it, so just set the desired mode prior to drawing.


This is the same way we handle HUDs in our FPS. :)


The only performance impact is that your are changing a uniform variable (your project matrix), right? So, just try to batch things to minimize state changes--same old stuff.


Friday, July 29, 2016

meaning in context - "The bass drop is so sick!..." - What does it mean?


Being a fan of a dubstep music, I often see comments like this:




"Looooove this tune! The bass drop is so sick!..."



To my understanding, sick has negative connotation. Merriam-Webster defines this word as "affected with a disease or disorder", either physically or mentally.


However, the phrase above looks rather positive (even if followed with something like "...my ears were bleeding").


What's the point?


Bass drop



Answer



Very good question. Generally speaking, this is an example of what we call slang. I'm sure your native language has it, too, but just to make sure we're on the same page:


Slang is a subset (superset? intersection?) of the English language used in informal settings. It does not require proper grammar, it allows skipping or adding words unconventionally, and, perhaps most importantly, it allows words to take on new definitions completely unrelated to their "real" definitions. These definitions simply evolve over time in the vernacular and really have no proper origins.



Some other examples of English slang words, all meaning roughly "very good", "impressive", etc. (I'm sure you're familiar with most):



  • wicked

  • awesome

  • boss

  • crazy

  • ridiculous

  • nasty

  • sick-nasty   (a personal favorite)



word usage - What do we call a person from a certain country?


Do we call a person from China "a Chinese"?


For example, can I say: I have a friend, he is a Chinese?




Thursday, July 28, 2016

Separate renderng thread in Android (OpenGL ES 2.0)


I'm used to mainly working with the Canvas SurfaceView API on Android and have recently been learning openGL ES 2.0


With canvas I know that surfaceView gives you the ability to start a new thread to render on, but it doesn't specifically do this for you, so I was creating a new thread and managing that thread when the app was ended / paused etc....



However, from what I've read with glSurfaceView it seems that this is actually done for you automatically? Does this mean I don't actually need to manually create / start and manage my own rendering thread? (I'm talking specifically about a rendering thread (which could also be used for logic updates) which is separate the main UI thread.


Clarification on this matter would be greatly appreciated.




c++ - Directx9, FBX sdk and indices problem


So I've set up my program, know how to get everything going except for one thing: indices. I've been stumped as to how I retrieve that set of data. Does anyone know what I function I need to get them? Thanks in advance!



Answer



Assuming you're using the latest fbx sdk, read:


http://www.gamedev.net/page/resources/_/technical/graphics-programming-and-theory/how-to-work-with-fbx-sdk-r3582


Fundamentally, the FBX sdk stores vertex and index data in a way that is not conducive for rendering api requirements in order save on repeated data. We have to construct the vertices themselves. To do this, for each vertex, retrieve the indices (mentioned in the above link), and construct your own 'vertex reference' structure, then store them in an array, and add an index to your index buffer. But before you do that, check to see if past vertices have any duplicated vertices (by comparing indices of the 'vertex reference' structure), in which case, use that index instead.


Wednesday, July 27, 2016

networking - Implementing an online database



I'd like to get into online games programming. I thought that as a start i'd be a good idea to implement an online database that would store the progress and score for a game i have made, i'll probably want to implement an account system too.


My issue is, i can't see to be able to ask google the right question. I don't know where to start. I've touched some on SQL and PHP, HTML and XSL, but, to me they're just languages, i can't see the big picture, how do these things connect to form a working service? I'm not looking for a solution, i just don't know what should i learn.


I'm not looking for knowledge on sockets, i'm familiar with network programming, i just don't understand the "modern" process of handling databases. I'd be very happy if somebody could lay out the structure of a database, how you put it out on the web, how you access the information and change it (not in a direct solution, just "this is done by programming a filter in SQL"), what languages are used for it, etc.



Answer



The database is the backend, your game is the client. Since you can't (well, technically you can but you really shouldn't) connect to the DB directly, you'll have to write some kind of middleware for that.


The middleware usually runs as a web-service or deamon on a server and exposes an interface for you to access/store game data. This stuff can be implemented in a lot of different languages.. basically any language that you can run on a server and access a database with.


For things like highscores, achievements etc. you can write a simple PHP (or Ruby, Java,..) script that you can access via HTTP. A common architecture for web APIs like this is REST. If you would implement a highscore system as RESTful service, you might have an URL like this:



http://my.server.com/highscores

Sending a GET request to that URL would fetch the scores from the DB and return them (you could send them as XML, JSON or similar).


To add a new score-entry, you maybe have an URL like:


http://my.server.com/highscores/add

And you would send a new Highscore to that address using a HTTP POST request. Then you read out the POST data and insert it into the database.


Of course you don't have to conform to any architecture (such as REST), but I'd say it's good practice.


Here are some things you should be aware of when you do something like this for the first time:





  • Don't trust the client. If your game can send a highscore, anybody else can do so also... this question touches on that topic.




  • Always validate and sanitize incoming data (remember, don't trust the client). Being sloppy with these things will make your service susceptible to SQL injection attacks.




xna - What are the cons of using DrawableGameComponent for every instance of a game object?


I've read in many places that DrawableGameComponents should be saved for things like "levels" or some kind of managers instead of using them, for example, for characters or tiles (Like this guy says here). But I don't understand why this is so. I read this post and it made a lot of sense to me, but these are the minority.



I usually wouldn't pay too much attention to things like these, but in this case I would like to know why the apparent majority believes this is not the way to go. Maybe I'm missing something.



Answer



"Game Components" were a very early part of the XNA 1.0 design. They were supposed to work like controls for WinForms. The idea was that you would be able to drag-and-drop them into your game using a GUI (kind of like the bit for adding non-visual controls, like timers, etc) and set properties on them.


So you could have components like maybe a Camera or a... FPS counter?... or...?


You see? Unfortunately this idea doesn't really work for real-world games. The kind of components you want for a game aren't really reusable. You might have a "player" component, but it will be very different to every other's game's "player" component.


I imagine it was for this reason, and for a simple lack of time, that the GUI was pulled before XNA 1.0.


But the API is still usable... Here's why you shouldn't use it:


Basically it comes down to what is easiest to write and read and debug and maintain as a game developer. Doing something like this in your loading code:


player.DrawOrder = 100;
enemy.DrawOrder = 200;


Is much less clear than simply doing this:


virtual void Draw(GameTime gameTime)
{
player.Draw();
enemy.Draw();
}

Especially when, in a real-world game, you might end up with something like this:


GraphicsDevice.Viewport = cameraOne.Viewport;

player.Draw(cameraOne, spriteBatch);
enemy.Draw(cameraOne, spriteBatch);

GraphicsDevice.Viewport = cameraTwo.Viewport;
player.Draw(cameraTwo, spriteBatch);
enemy.Draw(cameraTwo, spriteBatch);

(Admittedly you could share the camera and spriteBatch using the similar Services architecture. But that is also a bad idea for much the same reason.)


This architecture - or lack thereof - is so much more light weight and flexible!


I can easily change the draw order or add multiple viewports or add a render target effect, just by changing a few lines. To do it in the other system requires me to think about what all those components - spread across multiple files - are doing, and in what order.



It's sort of like the difference between declarative vs imperative programming. It turns out that, for game development, imperative programming is far more preferable.


opengl - Access vertex data stored in VBO in the shader


If I wanted to store extra data in a VBO for skinning (indices for indexing into an array of matrices of bones and floats for applying weights to those bones) How would I go about accessing that data in GLSL? I already know how to put the data in the buffer, interleaved with the rest of the data.


For example I want each vertex for a model to contain:


Vec3 position;
Vec3 normal;
Vec4 color;
Vec2 texCoords;
int boneCount;
int[3] boneIndex;

float[3] boneWeight;

Then drawing like:


bind(vertexBufferID);
glVertexPointer(3, GL11.GL_FLOAT, stridePlus, 0 * 4);
glNormalPointer(GL11.GL_FLOAT, stridePlus, 3 * 4);
glColorPointer(4, GL11.GL_FLOAT, stridePlus, (3 + 3) * 4);
glTexCoordPointer(2, GL11.GL_FLOAT, stridePlus, (3 + 3 + 4) * 4);
glVertexPointer(7, GL11.GL_FLOAT, stridePlus, (3 + 3 + 4 + 2) * 4);
glDrawArrays(GL11.GL_TRIANGLES, 0, VPNCTEnd);


Then in my vertex shader I want:


 //Get indices of bones
//Get weights of bones
//Get bone transforms
//for each bone transform, apply it to gl_Position at the specified weight

What is the GLSL required for the last part of the process? It seems like I need to set a attribute pointer to the data somehow, but I'm not sure where to do that when the data is stored in the VBO.



Answer



First of all, you probably want to use glVertexAttribPointer on the application side to specify all the components, including the bone stuff, rather than the deprecated glVertexPointer and friends. Something like:



glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, 0 * 4);  // Position
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, 3 * 4); // Normals
// etc.
glVertexAttribPointer(4, 3, GL_INT, GL_FALSE, stride, (3 + 3 + 4 + 2) * 4); // Bone indices
glVertexAttribPointer(5, 3, GL_FLOAT, GL_FALSE, stride, (3 + 3 + 4 + 2 + 3) * 4); // Bone weights

You don't need a separate attribute for the bone count, since you can just zero the weights of unused slots (and set the index to 0 or something). The first argument to glVertexAttribPointer is the attribute index, and each attribute can store up to 4 values.


You'll also need to use glEnableVertexAttribArray to tell OpenGL which attributes you're using.


In the GLSL shader, you then access these by declaring them as attribute variables, like:


attribute vec3 Position;

attribute vec3 Normal;
// etc.
attribute vec3 BoneIndices;
attribute vec3 BoneWeights;

Finally, you can control which variables are mapped to which attribute by using glBindAttribLocation. You'd insert a bunch of these calls before linking the shader, which will tell OpenGL the desired correspondence between the variables and the attribute indices used in the glVertexAttribPointer calls. (There are also other ways to set up this mapping; a more in-depth discussion is at this StackOverflow question.)


The usage of "among others"?


What is the general usage of "among others"? In my current understanding, I would say it is similar to "and so forth".





tiles - How do you generate tileable Perlin noise?


Related:



I'd like to generate tileable Perlin noise. I'm working from Paul Bourke's PerlinNoise*() functions, which are like this:


// alpha is the "division factor" (how much to damp subsequent octaves with (usually 2))
// beta is the factor that multiplies your "jump" into the noise (usually 2)
// n is the number of "octaves" to add in

double PerlinNoise2D(double x,double y,double alpha,double beta,int n)
{
int i;
double val,sum = 0;
double p[2],scale = 1;

p[0] = x;
p[1] = y;
for (i=0;i val = noise2(p);

sum += val / scale;
scale *= alpha;
p[0] *= beta;
p[1] *= beta;
}
return(sum);
}

Using code like:


real val = PerlinNoise2D( x,y, 2, 2, 12 ) ; // test


return val*val*skyColor + 2*val*(1-val)*gray + (1-val)*(1-val)*cloudColor ;

Gives sky like


nontileable


Which isn't tileable.


The pixel values are 0->256 (width and height), and pixel (0,0) uses (x,y)=(0,0) and pixel (256,256) uses (x,y)=(1,1)


How can I make it tileable?



Answer



There's two parts to making seamlessly tileable fBm noise like this. First, you need to make the Perlin noise function itself tileable. Here's some Python code for a simple Perlin noise function that works with any period up to 256 (you can trivially extend it as much as you like by modifying the first section):



import random
import math
from PIL import Image

perm = range(256)
random.shuffle(perm)
perm += perm
dirs = [(math.cos(a * 2.0 * math.pi / 256),
math.sin(a * 2.0 * math.pi / 256))
for a in range(256)]


def noise(x, y, per):
def surflet(gridX, gridY):
distX, distY = abs(x-gridX), abs(y-gridY)
polyX = 1 - 6*distX**5 + 15*distX**4 - 10*distX**3
polyY = 1 - 6*distY**5 + 15*distY**4 - 10*distY**3
hashed = perm[perm[int(gridX)%per] + int(gridY)%per]
grad = (x-gridX)*dirs[hashed][0] + (y-gridY)*dirs[hashed][1]
return polyX * polyY * grad
intX, intY = int(x), int(y)

return (surflet(intX+0, intY+0) + surflet(intX+1, intY+0) +
surflet(intX+0, intY+1) + surflet(intX+1, intY+1))

Perlin noise is generated from a summation of little "surflets" which are the product of a randomly oriented gradient and a separable polynomial falloff function. This gives a positive region (yellow) and negative region (blue)


Kernel


The surflets have a 2x2 extent and are centered on the integer lattice points, so the value of Perlin noise at each point in space is produced by summing the surflets at the corners of the cell that it occupies.


Summation


If you make the gradient directions wrap with some period, the noise itself will then wrap seamlessly with the same period. This is why the code above takes the lattice coordinate modulo the period before hashing it through the permutation table.


The other step, is that when summing the octaves you will want to scale the period with the frequency of the octave. Essentially, you will want each octave to tile the entire just image once, rather than multiple times:


def fBm(x, y, per, octs):

val = 0
for o in range(octs):
val += 0.5**o * noise(x*2**o, y*2**o, per*2**o)
return val

Put that together and you get something like this:


size, freq, octs, data = 128, 1/32.0, 5, []
for y in range(size):
for x in range(size):
data.append(fBm(x*freq, y*freq, int(size*freq), octs))

im = Image.new("L", (size, size))
im.putdata(data, 128, 128)
im.save("noise.png")

Tileable fBm Noise


As you can see, this does indeed tile seamlessly:


fBm Noise, Tiled


With some small tweaking and color mapping, here's a cloud image tiled 2x2:


Clouds!


Hope this helps!



c# - Unity Player Movement Y Axis(Something like Swing Copters)



My Player moves on Y AXIS , but sometimes it doesnt go up but stucks in one place, Script is like in swing copters , when you touch it rotates to another side but its on X Axis , i took and made it on Y axis , but it doesnt work properly , player sometimes doesnt turn around and go up or back Please help out , sorry for bad english


void MovePlayerOnYAxis()
{

foreach (Touch touch in Input.touches)
{


moveL = !moveL;


if (moveL)
{

transform.localScale = new Vector3(1, -1, 1);
}
else
{
transform.localScale = new Vector3(1, 1, 1);
}


huongbay = transform.localScale.x;
}
transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
}

Pre-Fix From @PompeyPaul But Player still doesnt go Down , it now goes only up.


void MovePlayerOnYAxis()
{

foreach (Touch touch in Input.touches)

{

WasTouched = !WasTouched;


if (WasTouched)
{
if (Input.touchCount == 0)
{
WasTouched = false;


transform.localScale = new Vector3(1, 1, 1);
}
}
else
{
if (Input.touchCount > 0)
{
WasTouched = true;
transform.localScale = new Vector3(1,-1, 1);

}

}
huongbay = transform.localScale.y;

}
transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
}


Tuesday, July 26, 2016

xna 4.0 - How to get file paths in XNA 4.0?


Is it possible to use OpenFileDialog in XNA 4.0 to get the file path? If not, what is the alternative? I'm using XNA 4.0 to create a graphic display (not a game) and I have a file that contains informations on how and what to draw on screen. The only problem is that I hard-coded the path because I don't know how to dynamically get that path? Do you know a solution for that?



Answer




Just put the Attribute [STAThread] above the Main method in the class Program and add the System.Windows.Forms in the References of the project.


After that you'll be able to instantiate and invoke the dialog boxes.


Multithreading in Gamedevelopment, specifically Networking


Let me quick explain my actual setup:


I use 2 Threads, one for networking and one for the main-loop (input, update, render). I have two synchronized queues, one for mainthread->networking and one for networking->mainthread. When a chunk of bytes arrives, the network-thread decodes a paket. The network-code knows, what each paket is and what it does. It now creates a functor to change the coordinates of an entity, to spawn a new one, or something else. It emplaces this functor in the queue and the main-tread executes every tick all the functors in the queue.


This kinda works for now, but i think i have to change this completely. I might split up some parts of the main-thread, input for example, and stick it in another thread. Also, i might want to add support for plugins written in lua, python or some other language, and i don't want the main-thread to get stuck when the plugin decides to run a long-running task. This would mean, eventually the main thread has to handle a decent number of queues, one for every thread plus one extra for the other direction (thread->main). Also, at the moment, the networking needs to have all the pointers to the data-structures it wants to control (For example, it has a ptr to the entitymanager stored, so it can create a functor to spawn a new entity in the entitymanager), thats kinda weird.


Are there common techniques to synchronize threads better? Especially since i have to provide a lot more control over the gamestate and still need to synchronize the other threads with the main-thread, i don't really see a better approach other then the functor-queue, so i hope for some suggestions.




Monday, July 25, 2016

XNA 4.0 - Why does using a RenderTarget2d cause transparency on models?


I have been working through Riemers ShadowMap tutorial and everything was going well until the section on drawing to a separate rendertarget. I am using a different model and quads but I assumed the process would still work.


If I draw the scene directly to the back buffer I get: Normal image


When I draw it first to a RenderTarget2D and THEN to the screen, I get this weird transparent effect only on the model, the textured primitives below are still rendered fine:


Weird transparency effect


The RenderTarget is defined:



PresentationParameters pp = device.PresentationParameters;
renderTarget = new RenderTarget2D(device, pp.BackBufferWidth,
pp.BackBufferHeight, true, device.DisplayMode.Format, DepthFormat.Depth24);

And it is used in this way:


protected override void Draw(GameTime gameTime)
{
device.SetRenderTarget(renderTarget);

device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);


DrawScene("Simplest");

device.SetRenderTarget(null);
shadowMap = (Texture2D)renderTarget;

device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
using (SpriteBatch sb = new SpriteBatch(device))
{
sb.Begin();

sb.Draw(shadowMap, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 1);
sb.End();

}
base.Draw(gameTime);
}

What gives?


Edit 1: I resolved the transparency effect by resetting:


device.DepthStencilState = DepthStencilState.Default;

device.BlendState = BlendState.Opaque;

But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.


Edit 2: Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency. Fixed with:


sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

Answer



Worked it out:


device.DepthStencilState = DepthStencilState.Default;
device.BlendState = BlendState.Opaque;


But now the model has a purple tint on the side away from the light. Something to do with my Shader code I presume.


Turns out the purple (blue) colour was a result of the window being cleared to .DarkSlateBlue and the RenderTarget having alpha transparency. Fixed with:


sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

opengl - How do I apply skeletal animation from a .x (Direct X) file?



Using the .x format to export a model from Blender, I can load a mesh, armature and animation. I have no problems generating the mesh and viewing models in game. Additionally, I have animations and the armature properly loaded into appropriate data structures.


My problem is properly applying the animation to the models. I have the framework for applying the models and the code for selecting animations and stepping through frames.


From what I understand, the AnimationKeys inside the AnimationSet supplies the transformations to transform the bind pose to the pose in the animated frame. As small example:


Animation {
{Armature_001_Bone}
AnimationKey {
2; //Position
121; //number of frames
0;3; 0.000000, 0.000000, 0.000000;;,
1;3; 0.000000, 0.000000, 0.005524;;,

2;3; 0.000000, 0.000000, 0.022217;;,
...
}
AnimationKey {
0; //Quaternion Rotation
121;
0;4; -0.707107, 0.707107, 0.000000, 0.000000;;,
1;4; -0.697332, 0.697332, 0.015710, 0.015710;;,
2;4; -0.684805, 0.684805, 0.035442, 0.035442;;,
...

}
AnimationKey {
1; //Scale
121;
0;3; 1.000000, 1.000000, 1.000000;;,
1;3; 1.000000, 1.000000, 1.000000;;,
2;3; 1.000000, 1.000000, 1.000000;;,
...
}
}


So, to apply frame 2, I would take the position, rotation and scale from frame 2, create a transformation matrix (call it Transform_A) from them and apply that matrix the vertices controlled by Armature_001_Bone at their weights. So I'd stuff TransformA into my shader and transform the vertex. Something like:


vertexPos = vertexPos * bones[ int(bfs_BoneIndices.x) ] * bfs_BoneWeights.x;

Where bfs_BoneIndices and bfs_BoneWeights are values specific to the current vertex.


When loading in the mesh vertices, I transform them by the rootTransform and the meshTransform. This ensures they're oriented and scaled correctly for viewing the bind pose.


The problem is when I create that transformation matrix (using the position, rotation and scale from the animation), it doesn't properly transform the vertex. There's likely more to it than just using the animation data. I also tried applying the bone transform hierarchies, still no dice. Basically I end up with some twisted models. It should also be noted that I'm working in openGL, so any matrix transposes that might need to be applied should be considered.


What data do I need and how do I combine it for applying .x animations to models?


I've made some mock ups of what this looks like, in case that's useful.


First I wanted to just test the translation, this is a bobbing head, what it looks like in Blender:



http://i.stack.imgur.com/NAc4B.gif


And what it looks like in game (don't mind the colors):


http://i.stack.imgur.com/nj2du.gif


Then for just rotation, the animation was the head rotating 360 degrees around the vertical axis. This is what that looks like in game:


http://i.stack.imgur.com/gVyUW.gif


Note, there should be no tilt, only rotation like a merry-go-round.


Update


I have the translation part of the animation working. But it feels kind of hacky and I don't see how to apply it to the rotation.


The translation works by taking these steps:




  1. Take the position from the animation frame and swap the y and z values

  2. Translate the transformation matrix by the altered position

  3. Transpose the transformation matrix

  4. Apply the transformation matrix to the vertices


So that's how it can work, but how is it supposed to work generally for position, scale and rotation?



Answer



OK, I put some more time toward this and got it working for multiple bones, and considerably less hack-like (though still a little). The system I had in place originally was almost correct. However, the main problems were:



  1. Blender saves Quaternions in W, X, Y, Z format. I was loading them X, Y, Z, W.



  2. My code for converting a Quaternion to a matrix was incorrect. I'm actually still not sure why this is incorrect, but I know the following code works, as part of my Quaternion class:


    public Matrix4f toMatrix() {
    Matrix4f tmpMatrix = new Matrix4f();
    if (this.length() > 0)
    this.normalise();

    float xx = this.x * this.x;
    float xy = this.x * this.y;
    float xz = this.x * this.z;

    float wx = this.x * this.w;

    float yy = this.y * this.y;
    float yz = this.y * this.z;
    float wy = this.y * this.w;

    float zz = this.z * this.z;
    float wz = this.z * this.w;
    //note the "* -1"s
    //I needed those to make the same matrices Blender was expecting

    tmpMatrix.m00 = (1.0f - 2.0f * (yy + zz)) * -1;
    tmpMatrix.m01 = ( 2.0f * (xy - wz)) * -1;
    tmpMatrix.m02 = 2.0f * (xz + wy);
    tmpMatrix.m03 = 0;

    tmpMatrix.m10 = 2.0f * (xy + wz);
    tmpMatrix.m11 = 1.0f - 2.0f * (xx + zz);
    tmpMatrix.m12 = ( 2.0f * (yz - wx)) * -1;
    tmpMatrix.m13 = 0;


    tmpMatrix.m20 = 2.0f * (xz - wy);
    tmpMatrix.m21 = 2.0f * (yz + wx);
    tmpMatrix.m22 = (1.0f - 2.0f * (xx + yy)) * -1;
    tmpMatrix.m23 = 0;
    return tmpMatrix;
    }


Other than that, it's just:


finalMatrix = boneMatrix * skinMatrix * invertedBindMatrix;



Note that the boneMatrix should be using the animated matrices for each bone instead of the bind matrices. It should also get all it's parent matrices like so:


private Matrix4f getBoneMatrix() {
if (parent == null) {
return Matrix4f.mul(Matrix4f.mul(parentArmature.getBindMatrix(), parentArmature.getArmatureRootMatrix(), null), boneMatrix, null);
} else {
return Matrix4f.mul(parent.getBoneMatrix(), boneMatrix, null);
}
}

And it works. Leave a comment if you need clarification.



sentence construction - Usage of the phrase "whether it is"


Many people use the phrase "whether it is" to introduce lists or alternatives at the beginning of sentences.


Can we also use "whether it is" in this way in other sentence positions such as in the following sentence:



Unfortunately, human beings have limited ability to prevent an unhappy experience from happening in life, whether it is disease, injury, or the death of a family member.






Trying to load .json questions and answers into a multiple-choice quiz game in Unity


I am developing a Unity game which includes a multiple-choice quiz.


I've placed what I believe is a properly-formatted .json file (the quiz question, four answer choices, the correct answer, and an explanation for the answer) (which I checked with a .json formatter) in the StreamingAssets folder in the Unity project. I've created a custom class for the question, the four answer choices, the correct answer and the explanation of the answer.


I am trying to load the entire contents of the .json file into an array, "questions," then copy that array into another array, "questionsCopy." To avoid repeating questions, as a question is used during the gameplay, I will remove it (and its corresponding answer choices, correct answer and explanation) from the questionsCopy array. (I have not yet developed the GUI to show the question, answer choices and eventually the correct answer and its explanation.)



Here are relevant sections of what I've coded so far:


1) The custom class:


// This is the custom class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class QuestionChoicesAnswerHintExplanation : MonoBehaviour {


public string[] question; // An array of strings (rather than just a string) so that line spacing, which doesn't play well with .json, could be preserved
public string[] answerChoices;
public int correctAnswerIndex;
public string explanation;
}

2) From the GameController:


public QuestionChoicesAnswerExplanation[] questions; // This is the fixed size array of the questions, answer choices, answers, and explanations.
private static List questionsCopy; // This is the resizeable list (originally a copy of the array). The size of this list will diminish as we remove items after presenting each question.
private QuestionChoicesAnswerExplanation currentQuestion;


string path; // The path to the .json file storing the questions, answer choices, correct answer index, explanations.
string jsonString; // The contents of the .json file.

In the Start() in the GameController:


    path = Application.streamingAssetsPath + "/questionsAndAnswers.json";
jsonString = File.ReadAllText(path);

questions = JsonUtility.FromJson(jsonString);


// Debug.LogWarning("Questions:");
Debug.LogWarning(questions);

if (questionsCopy == null || questionsCopy.Count == 0) // A list with zero elements isn't always null.
{
questionsCopy = questions.ToList();
}

PickRandomQuestion();


Further down in the GameController:


    public void PickRandomQuestion()
{
int randomIndex = Random.Range(0, questionsCopy.Count);
currentQuestion = questionsCopy[randomIndex];
questionsCopy.RemoveAt(randomIndex);
}

3) Here are the contents of the .json file in the StreamingAssets folder:


{

"questions":

[

{
"question": ["Trinculo admits 'I have been in such a pickle...' in this comedy:"],
"answerChoices": ["'The Tempest'", "'Henry 4, Part 1'", "'Henry 5'", "'The Merry Wives of Windsor'"],
"correctAnswerIndex": 0,
"explanation": "'Henry 4, Part 1,' and 'Henry 5, are both histories. To be in 'a pickle' usually means to be in a quandary. A broader view of this passage reveals Trinculo to be drunk: \n\nAlonso: \nAnd Trinculo is reeling ripe: where should they \nFind this grand liquor that hath gilded 'em? \nHow camest thou in this pickle? \n\nTrinculo: \nI have been in such a pickle since I \nsaw you last that, I fear me, will never out of \nmy bones: I shall not fear fly-blowing.' \n\n'The Tempest' 5.1."
},

{
"question": ["In 'Hamlet,' this character remarks: 'Neither a borrower nor a lender be; \nFor loan oft loses both itself and friend, \nAnd borrowing dulls the edge of husbandry. \nThis above all: to thine own self be true,\nAnd it must follow, as the night the day,\nThou canst not then be false to any man:'"],
"answerChoices": ["Fortinbras", "Gertrude", "Polonius", "The Ghost of Hamlet's Father"],
"correctAnswerIndex": 2,
"explanation": "The verbose Polonius is speaking to his son Laertes. 'Hamlet' 1.3."
},
{
"question": ["Roger Daltrey, well into his career with The Who, played the roles for both Dromios, the twin servants, in a 1983 BBC production of:"],
"answerChoices": ["'King John'", "'King Lear'", "'Coriolanus'", "'The Comedy of Errors'"],
"correctAnswerIndex": 3,

"explanation": "'The Comedy of Errors.'"
}

]
}

BUT I'm getting an error:



ArgumentOutOfRangeException: Argument is out of range. Parameter name: index


Parameter name: index System.Collections.Generic.List`1[QuestionChoicesAnswerExplanation].get_Item (Int32 index) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/List.cs:633) GameController.PickRandomQuestion () (at Assets/Scripts/Managers/GameController.cs:741) GameController.Start () (at Assets/Scripts/Managers/GameController.cs:99)




The error message points to problems (GameController.cs:741 and GameController.cs:99), but I don't see what's wrong there. I am UNSURE about the message regarding line 633.


And the Debug.Logwarning yields this:



QuestionChoicesAnswerExplanation[] UnityEngine.Debug:LogWarning(Object) GameController:Start() (at Assets/Scripts/Managers/GameController.cs:92)



What need I do to fix this? Thank you.




Using definite article before abbreviations


Consider this part of a technical article.



Approaches to boilerplate detection typically exploit DOM- level features of segments by means of handcrafted rules or trained classifiers, or they identify common, i.e., frequently used segments or patterns/shingles on a website ..... Yi et al. simplify the DOM structure by deriving a so-called Site Style Tree which is then used for classification [26]. Baluja [2] employs decision tree learning and entropy reduction for template detection at DOM level.



DOM is abbreviation for Document Object Model, in this article sometimes it is used with "the" and sometimes without it, Why? As I checked another document, they may use the DOM tree but DOM trees.


I guess as the DOM tree and the DOM structure is unique, they use "the"



In general, are there rules for definite article and abbreviations?




Sunday, July 24, 2016

c# - How can I implement hexagonal tilemap picking in XNA?


I have a hexagon tiled map in which I need to check when a hexagon is clicked. The hexagons aren't actually touching, rather they have a slight gap in between each of them.


Does anyone know how could I go about checking whether a hexagon is clicked without over complicating the whole thing?



Answer



Take a look to this picture


hexagonal decomposition


As you can see there is a relatively intuitive way to map x,y rectangular coordinate system to the hexagonal one.


We may talk about "rect" irregular hexagons ie hexagons inscribed in ellipses or hexagons obtained from regular hexagons scaled in both directions disproportionately (no rotations-shearings).


A rect hexagon can be defined by the height and width of the circumscribing rectangle plus the width of the inscribing one. (W,w,h)



inscribing/circumscribing rectangles


The easiest way to find out the hexagonal index is to partitionate the space as follow:


space partition


The rectangle width is w + (W - w)/2 = (w + W)/2, its height is h/2; the width of the green rectangle is (W-w)/2. Is easy to find out where in which rectangle the point falls:


enter image description here


u and v are the reminder coordinates that indicates where the point is whithin the i,j rectangle: Using w we can say if we are in the green area (u < (W-w)/2) or not.


if it is the case we are in the green area we need to know if we are in the upper or lower half of the hexagon: we are in the upper half if i and j are both even or both odd; we are in the lower half otherwise.


In both cases it is usefull to trasform u and v so they vary between 0 and 1:


enter image description here


if we are in the lower half and v < u



or


if we are in the upper half and (1-v) > u


then we decrement i by one


Now we simply have to decrement j by one if i is odd to see that i is the horizontal hexagon index (column) and the integer part of j/2 is the vertical hexagon index (row)


enter image description here


word meaning - huge or large. Which one should I use?



  • There were huge machines at his plant.

  • There were large machines at his plant.



Which one sounds better? Are they both grammatical? Could you please explain any differences between the two as they are both very confusing for me.



Answer



Of course, both sentences are grammatical. "Huge" and "large" are in the same category: they are adjectives. However, something huge is surprisingly large or excessively large. If something is large, but about as large as can be expected, then it is not huge.


Huge is an emphatic word, and has subjective connotations: what one person might call big --- or even small! --- someone else might call huge. A teenage girl about to go to a dance might think she has a "huge" zit (acne spot) on her chin, but to someone else it might appear small and insignificant.


For instance, have you ever heard of someone ordering a "huge coffee" in a coffee shop? If there were such a thing on the menu, it would be understood as humor. Even ridiculous drink sizes like 64 oz drinks are not called "huge", but "super sized" or whatever.


Or how about clothing: a T-shirt can be "large", and then "extra large". "Huge" is not used because it's an emotional word; it does not work well with cold facts like objectively established sizes, and could even be offensive to someone because of its possible connotations of "excess".


c# - Rendering arbitrary text in XNA using Windows API?


In Andrew's comment on my other question, he noted that it was possible to render text to a Texture2D using the Windows API, instead of drawing the text directly with a SpriteBatch. How is this done? I'm guessing there's an intermediate step before writing the image data to a Texture2D.


I'm asking because this would allow me to render Unicode characters on-the-fly, instead of needing to pre-render all the needed glyphs using a SpriteFont (too many glyphs in Korean and Japanese to make this route infeasible, sadly). Thanks!



Answer



Using some reflection, you can grab the Direct3D surface pointer from a Texture2D. From there, you can use any APIs that can render to a DX surface. I did this recently to host XNA content with WPF's D3DImage (with alpha channel support). DirectWrite can render to a DX surface, and you might even be able to use managed APIs. The DirectX .NET wrappers in that link only support Direct3D 10 and 11, and not Direct3D 9 (which XNA uses AFAIK). However, you still might be able to get it to work. On a side note, if you want to render vector graphics, you may be able to use a similar approach to interoperate with Direct2D. Naturally, none of this will work on any XNA-supported platform other than Windows.


Past tense: learned/learnt, dreamed/dreamt?


In my very first question, Carlo made an edit stating that learnt is a rare past tense of learn. I am accustomed to using learnt for past tense and learned as an adjective (as in He is a learned scholar.) I checked into a couple of dictionaries and they say both are valid past tenses. Do I stand a risk of not being understood if I use learnt?


In a similar vein, should dreamed be used as a past tense for dream instead of dreamt? I can't think of other such conflicts, but I guess there must be more.




Answer



Both are valid. learned is consistently more commonly used in American English:


enter image description here


In British English the difference has traditionally been much closer, with both being roughly equivalent, however since the 1940s, learned has become the dominant choice.


enter image description here


game industry - Starting career with enough education but no experience?


I am a student in Game Programming at University and a lot of students like me are wondering the best way of entering the industry. With a bachelor degree in game programming, but no real experience in the game industry, how can students begin developing real projects ?



Major game companies requires you to have 2 - 3 years of experience, so how do you guys suggest us to make our way through this selective industry ? Start in smaller buisness ? Build a kick-ass demo could maybe be enough ? Massively read all game programming books we can ?


Thanks for your suggestions, the question is yours !



Answer



As someone trying to get into the programming side you've got two main options.


Internships


Look for any internships you can find with game companies in your area. These are a great way to get your foot in the door. Many larger publishers use internships as a try-before-you-buy plan with students. If you can prove yourself in a real production situation then you will often find a job offer at the end of that internship, if the company has open slots.


However, please come into it with mindset to learn as much as you can. There are few things more annoying than a student who has spent a couple years in school and thinks they know how everything works.


Make Something, Show your Passion!


When looking at two inexperienced candidates if one of them has some software they can show that's certainly a leg up on someone that has nothing. It doesn't have to be a finished game, but obviously if another candidate has a game and you don't that looks better on them. Most importantly it needs to be easily demonstrated (have video of it running as well as the code) and you should be able to clearly explain what you did.


Note, you've likely made some projects in school, but so has everyone else and often similar projects. I'd advise against showing those unless they are very good, or you've taken them far beyond the class requirements. Think about the message you send with what you show. Class work says, "I couldn't be bothered to do more than the minimum." That's not the message you want to send.



Saturday, July 23, 2016

c# - Rotate an object smoothly on the Y axis in Unity


I am attempting a simple script to swing a door open in Unity. This requires a smooth rotation of 90 degrees around the Y axis. I have seen that one way to do this is using Unity's Quanternion object. I believed that this should work:


public class DoorOpenScript : MonoBehaviour 
{

public float smooth = 20;

// Use this for initialization

void Start ()
{
SwingOpen ();
}

// Update is called once per frame
void Update ()
{

}


void SwingOpen()
{
Quaternion newRotation = new Quaternion(transform.rotation.x,transform.rotation.y,transform.rotation.z,transform.rotation.w);;
newRotation *= Quaternion.Euler(0, 90, 0); // this add a 90 degrees Y rotation
transform.rotation= Quaternion.Slerp(transform.rotation, newRotation,20 * Time.deltaTime);

}

}


However, this just opens the door completely. I have tried playing with the third parameter to Slerp but with no results. What am I doing incorrectly?



Answer



Think about what you need to do, open the door over time. It's not going to happen all in one call in the Start function. You'll need to add a little more rotation each frame to rotate the object smoothly. Something like the following will rotate the object from 0 to 90 degrees over time:


void Update () {
SwingOpen();
}

void SwingOpen()
{

Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
transform.rotation= Quaternion.Slerp(transform.rotation, newRotation, .05f);
}

Notice it's using the Update() function instead of Start(). That's because we want to change it a little each frame. Using Slerp you'll notice that the object swings fast at first, then slower until finally reaching its rotation. The last parameter controls that rate of change, with 1 being instantly and 0 being never.


Perhaps this is your intended behavior, if not you can also perform a constant rotation over time with something like the following:


public float rotationDegreesPerSecond = 45f;
public float rotationDegreesAmount = 90f;
private float totalRotation = 0;
// Use this for initialization

void Start () {

}

// Update is called once per frame
void Update () {
//if we haven't reached the desired rotation, swing

if(Mathf.Abs(totalRotation) < Mathf.Abs(rotationDegreesAmount))
SwingOpen();

}

void SwingOpen()
{
float currentAngle = transform.rotation.eulerAngles.y;
transform.rotation =
Quaternion.AngleAxis(currentAngle + (Time.deltaTime * degreesPerSecond), Vector3.up);
totalRotation += Time.deltaTime * degreesPerSecond;
}


In this case, the rotation of the door will take 2 seconds to reach 90 degrees.


And just a tip, setting the variables to public will allow you to edit them from the Unity editor. This means you can apply this same script to multiple objects, but change the values for each object without editing the script.


geometry - Perspective in early pseudo-3d games


Please take a look at the screenshot below, from the old classic Space Harrier. My question regards the curved perspective on the chequerboard 'ground'. It's got a strangely curved geometry (I remember seeing this in a few old games/demos). I reminds me somewhat of a moire effect, and I think some of it (in the background) is just that - but I don't think its the full story. Compare with the screen shot from the Sega version, which shows moire effects in the distance, but not the same curvature.


So...



  • Why the curvature?

  • Did they do this on purpose, or is it a side effect of some technique?


  • How is it achieved?


Space Harrier - C64 Space Harrier - Sega




word usage - Difference Between "In Time" and "Before Time"


My boss gave me a task with completion date suppose 31 March, 2017and I completed on 28 February, 2017. Is it in time or before time.




sentence construction - How to write our home address in formal forms


If I write the address as below:


No 21, 15 Alpha St, Babol, Mazandaran, Iran what does it mean?





  1. There are multiple Alpha Streets and I am living in the 15th brunch.( I think this is correct)






or





  1. There is a single street having the name "15 Alpha".






Question:


If (1) is true, what should write if there is only a single street having the name "15 Alpha" and I live in.




Additional Info:


"21" is the house number.


"15 Alpha" is an important date in Iran History which is considered for the name of a street.



Answer



I think the exact method of writing addresses depends very much on local custom. In the US, UK, Canada, and Australia, the normal form is something like this:




522 3rd Avenue #4

This means



  • the street is "3rd Avenue"

  • the house number is 522; that is, this is the 522nd building on 3rd Avenue

  • the number of the apartment (or flat, or unit) within the building is 4.


We don't usually say or write out "number" or "No." for the house number except in a few famous cases like Number 10 Downing Street (where the executive branch of the government of the UK is headquartered).


The issue in your case arises because in English-speaking countries we don't usually begin street names with a number! If the street name itself is a number, like 3rd Street or 5th Avenue, we usually write it as an ordinal, like 1st, 2nd, 3rd, etc.



To answer one of your original questions, if the street is really named "15 Alpha Street", then no, I would not assume that there are multiple Alpha Streets. The US has a few "4th of July" roads and Montevideo, Uruguay has streets like "18 de Julio"; I don't think anybody thinks there is also a "5th of July" road and a "19 de Julio" avenue.


But if the street name itself begins with a number, like "15 Alpha Street", then something like


20 15 Alpha Street

becomes very confusing, because we're only used to seeing one number before a street name, and that number is the house number. If there is only one "15 Alpha Street", then I would write out the address like
No. 21, 15 Alpha St
Babol, Mazandaran
Iran

meaning in context - How cold is a dish that is served cold?



There are several dishes that are best served cold.


But, does this usually mean the "normal room temperature", or cold as in "frozen", or as when the food just comes out from a freezer or a fridge?


The latter is my default understanding.


So, one of our answers saying "Ketchup is usually served cold." made me curious because it sounds more like "room temperature".


How cold is a dish that is served cold?



Answer



As with so many things, it depends.


When used in contrast to a hot alternative, cold simply means at or somewhat below room temperature. For example, the meat in a hot pastrami sandwich is heated on a skillet as part of its preparation and served hot, whereas a cold pastrami sandwich it is not.


Food is also cold if it is usually served heated, but has cooled off below the temperature where it is normally consumed. Thus, your lukewarm chicken noodle soup may still be warmer than the air, but you may still send it back to the kitchen as "cold."


If the temperature of a food were deliberately lowered as part of its preparation, with ice or refrigeration, it would be chilled. For example, you might have chilled wine served with your dinner and chilled fruit for dessert.



Sometimes, hot and cold distinguish between levels of preparation. A cold lunch would be one brought from home (aka sack lunch), or a box lunch of a sandwich or fruit, as opposed to a hot lunch which would be a heated, prepared meal. Schools may offer a choice of hot lunch or cold lunch, for example.


Ketchup is a condiment, and so would almost always be cold, but would probably not be chilled.




I should note that with beverages as opposed to food, cold does sometimes mean chilled, at least in American English. You'll advertisements for cold drinks, typically meaning chilled fruity or fizzy soft drinks. A cold beer is idiomatically one that has been chilled below cellar temperature (well below room temperature)— we would not order chilled beer in a bar without raising some eyebrows.


But there are certain drinks which are taken hot or chilled, and never at room temperature. Thus, cold coffee or cold cider is hot coffee or cider that has been allowed to cool off— not something you can typically order. To get the truly cold alternative, you order iced coffee or chilled cider.




Lastly, there is the expression Revenge is a dish best served cold, but cold here is a play on words, referring to cold-bloodedness (i.e. heartlessness or mercilessness).


slang - How to learn English in quick way



I am not very good with the English language. I have three questions:




  1. While talking to others, most of them ask me why I am talking in much too complex a fashion (that is, they are not understanding my English). They suggest that I try to speak simpler English. I don't know how to talk simple English to make others understand me quick & easy.




  2. I am not able to understand American slang.





  3. Myself, I want to improve my communication and written skills.




Can someone suggest me how to improve these skills? My mother tongue is Tamil.



Answer



My short answer: Don't worry.


Here is my longer answer. I was exactly in your shoes in the first few years I started to work with people from other countries. Some of them mentioned that I tended to use too many words. My sentences were too long, and so on. And, if I wanted to say something complex, it was too easy that they will not understand my English too.


Back then, I didn't know how to solve the problem on my own.


But I found that the more I watched movie, the shorter, and more natural my speech became.



I'm lucky because I'm a movie lover.


But I believe that if you can find what you like, and keep watching it, or listening to it, and stick with it, your English will improve little by little. (Here is my big tip. If you want to improve really fast, focus on your listening.)



  • I believe that today, you have another good alternative: chat rooms. You can find a chat room on about everything. Just find a chat room that you are interested in its topic. Freenode is a good starting point. Mingling with people in chat rooms can improve your English too.


Fix your speaking first, writing skill will improve naturally. And, when you are confident enough with your speaking, you can start taking grammar seriously. At that point, grammar will not be something irrelevant anymore.


Good luck with your learning. :)


Friday, July 22, 2016

fronting - Putting the verb in the beginning of the sentence to emphasize it



Gone are the hardware concerns of A, yet with B, you control the application.



Is it that kind of a construction when to emphasize a term you put it in the beginning of the sentence and put the verb after it?


So the normal sentence would look:



The hardware concerns of A are gone, yet, with B, you control the application.





Answer



That is an old-fashioned literary use which you are unlikely to encounter in contemporary written English, much less conversation. It does emphasize the gone; but this is not because it is first but because it is so oddly placed.


Other things being equal, the strongest position in any clause is the final one, not the first, because in the simplest sentences this is where "new" information normally falls.


textures - OpenGL ES 2.0. Sprite Sheet Animation


I've found a bunch of tutorials on how to make this work on Open GL 1 & 1.1 but I can't find it for 2.0.


I would work it out by loading the texture and use a matrix on the vertex shader to move through the sprite sheet.


I'm looking for the most efficient way to do it. I've read that when you do the thing I'm proposing you are constantly changing the VBO's and that that is not good.


Edit: Been doing some research myself. Came upon this two Updating Texture and referring to the one before PBO's. I can't use PBO's since i'm using ES version of OpenGL so I suppose the best way is to make FBO's but, what I still don't get, is if I should create a Sprite atlas/batch and make a FBO/loadtexture for each frame of if I should load every frame into the buffer and change just de texture directions.



Answer



One way to do sprite animation with OpenGL ES shaders is achieved by using uniforms and changing texture coordinates in the vertex shader. To elaborate, suppose you have a 1024x128 sprite sheet with 8 frames.



  1. Set up a quad whose vertices (clockwise) are (-1, -1), (-1, 1), (1, 1), (1, -1).


  2. Assign texture coordinates to the vertices with (0, 0), (0, 1), (1, 1), (1, 0), respectively.

  3. In the vertex shader, define a uniform iSpriteFrame which is set to the frame of the sprite animation you wish to draw (between zero and seven for this example).


  4. When you draw the sprite at frame n, for each vertex with texture coordinate tc and position p, calculate the final texture coordinate ftc with


    ftc.x = (iSpriteFrame + tc.x) * 0.125
    ftc.y = tc.y


c# - How do dialog trees work?


That is, what is connected to what and how to move between lines of speech when a sub-conversation ends?


If you have any examples of a basic dialog tree in C#, please post them.



Answer



The name "dialogue tree" is a bit misleading - they usually are simple directed graphs, not just trees. The basic data structure of such graphs usually consists of some kind of "data" for the nodes, which represent the points we are at in the conversation, and links from them to other nodes, which represent what is being said and done by the participants and optionally have conditions on them to limit their visibility or scripts to perform various additional actions. Usually one of the nodes is the default starting node (typical labels for that are "ROOT", "START" and "GREETING"), and nodes which have no valid links leading from them end the conversation.


In most cases, the graph is represented in-memory as a list of Node data structures, each having at least an ID and a list of 0..n Link data structures. The list can be local to the NPC or a global one; the second case is preferred if you have lots of generic NPCs which can be talked to for information, but offer no specific conversations on their own. The system itself finds the starting conversation node for the NPC, remembers its ID as the current conversation ID, presents the currently valid links for the player to chose from (or "[end conversation]" if there are no valid links) and waits for input. When the player chooses a link, the associated dialogue lines get displayed and any associated scripts run.



Instead of having complex rules and conditions on links, you can instead get by with a simple "valid" boolean variable, which can be then changed from either the scripts of other conversation links (including the default one from the starting node) or by outside mechanisms. In general, this approach is simpler but only suitable for games with very few such conversations, since it moves the logic of "When is this response possible?" away from the response data itself.




Note that the structure I describe here is slightly different from Byte56's in that the nodes don't need to have any dialogue lines; the links can have them all. In the most basic variant, this translates to the following structure.


enter image description here


negation - Difference between "no" and "not"


Please tell me which of the following sentence is correct and why?





  • It is no good asking him for help.

  • It is not good asking him for help.



Please explain the usage of no and not. Are they adverbs or adjectives or something else?




Thursday, July 21, 2016

american english - Punctuation inside quotes: Should I put the period inside quotes, if the sentence ends with a question mark or an exclamation point?



In American English, a period is not added at the end of a sentence if it ends with a quote whose last letter is a quotation mark or an exclamation point.



Edema asked, "Am I an alliteration addict?"



Should the period at the end of the quote be added, if the sentence ends with a question mark or an exclamation point? Is the following sentence correct?



Did Edema said, "I am an alliteration addict."?




Answer



In this case you remove the punctuation from the quote, so the period would go away and the question mark would remain. (Also note it should read Did Edema say, not Did Edema said.)



So the corrected version of the sentence would be:



Did Edema say "I am an alliteration addict"?



3d meshes - Creating a basic character skeleton from code


I'd like to have a procedural system that uses a string of data to create a 3d creature. The way I've thought to do this is to use the code to generate a simple creature skeleton (I'll get to the skin generation when I have time) so I can test different source data's effect on the structure produced.


How can i use a set of data to generate the simple 3d skeleton?


The code would have information used to show what type of bone it was(hierarchy), the bone length, and how the bone was positioned and use this to make the model. (At least in planning, I don't know how to implement it)


Edit: The goal is to create creatures of different forms and skeletons. The creation will be mirrored down the spine so both sides are the same.


I'd like it to be highly adaptable but I'd like to specify a max of 4 legs and 4 arms (8 limb max only 4 on ground for walking). Being able to create a basic structure for humanoids, quadrupeds, and mixes (like a centaur or biped with no arms) is the goal.


I've looked for how to create a model off of the code procedurally, looking at stuff like FRep isosurfaces and metaballs, but I'm stumped on how to make it happen. I decided any progress is better that none, so I'd like to get a generator for something like an animators skeleton example to make sure I can get working structures (and later have something to work with to begin working on the animation algorithm).


Sorry for the lack of information at first, I was trying to keep the question simple. If you have an idea for the creation of the structure(skeleton) or maybe even the form itself I'd appreciate the help. Thanks




phrase usage - "I hate red color" or "I hate red": why exactly is the first option ungrammatical


If a person wants to say that the most hated color for him is red (in general, no specific hues implied), could he say:




  1. I hate red color.



I've found very little results for this sentence at Google. Is this combination (red color) very awkward in its effect?



I guess the natural way is to say:




  1. I hate red.



But it's interesting why exactly the combination "red color" is unnatural in English in this context. In Russian, a similar phrase would be perfectly okay.


Is it because color calls for an article, and this would in turn call for the continuation of the sentence:





  1. I hate the/a red color of ... (something).



I've been proofreading one text at lang-8 and found myself unable to explain in simple words why hating "red color" could be an unnatural phrase.



Answer



When "red" is followed by a noun, native English speakers will classify "red" as an adjective. If that noun is then singular (and the noun phrase is undetermined, i.e. has no definite article, indefinite article, or other determiner like "this" or "your" or something), then native English speakers hear the sentence as ungrammatical.



I hate red bicycles.



This one is grammatical because bicycles is plural. It is therefore like saying I hate bicycles but with the qualification that the bicycles are red.




I hate red meat.



This one is grammatical because meat is a mass noun, meaning it applies to a quantity of something, not a single something.



I hate red telephone.



This one, like I hate red color, sounds wrong because telephone is singular.


Wednesday, July 20, 2016

"High quality" usage


According to http://www.phrasemix.com/phrases/something-is-of-high-quality ,



It is high quality.



or



It is of high quality.



are both OK, but clearly the first is ungrammatical. Is it really normal to say the first, or sounds a little bit odd and is used seldomly?




Answer




It is high quality.



There is nothing wrong with this. Quality is an adjective and high is an adverb modifying quality. Adjectives are OK after to be since to be is a copular verb and can take subject complements.



It is of high quality



It's also fine for a subject complement to be a prepositional phrase. The prepositional phrase's object is the sentence's subject.


So, what's the difference in meaning?



"X is high quality" - You are saying X has the attribute high quality. No implication, and this is best if the attribute high quality is inherent to X.


"X is of high quality" - You are implying X has the attribute high quality compared to those in group of other X's, or you are implying something used to make X has given X the attribute high quality.


Tuesday, July 19, 2016

Plural of belief: beliefs or believes?


I found usages of both "beliefs" and "believes" and am confused while using a plural of 'belief'. So, I want to know which is the correct plural of 'belief'? Is it believes or beliefs?



Answer




Actually they are different.




  1. Believe is a verb which is simply used for accepting the truth.



    Example: He believes that all ​children are ​born with ​equal ​intelligence.



    In above example the word "believes" is used as a third-person singular simple present.





  2. Belief is a noun which is generally used for acceptance/confidence in truth, faith or trust.



    Example: I can't do that. It's against my beliefs.



    In above example, the word "beliefs" is used as plural of belief.




So, The difference is:



  • Beliefs is the plural of a noun belief


  • Believes is the use of a verb believe in third-person singular simple present


Ghost replay - storage and timing


I am working on a car race game and just implemented a ghost sprite for replaying past races. I use a physics engine and after much reading I came to the conclusion that the best way to store the ghost data for replay would be to record the car's position and rotation at given timepoints, as for example described here: https://gamedev.stackexchange.com/a/8380/26261.


But what would be a good way to find those timepoints during replay? An example would be a record with this data:



time: +3.19932 (seconds since race start)
position: 180,40 (position at that time)
rotation: 30.4 (rotation at that time)

But I have several problems with that:




  1. When I replay, it's unlikely that I reach the exact timepoint at 3.19932 again - more likely, I will have a timepoint around 3.1 and have to find the closest matching record. When interpolating, even the closest matching above and below. This sounds very inefficient and time consuming?





  2. In which list structure could I store these records for a later replay? An array? Doesn't that mean that search time for records matching a certain time will increase the longer the race is?




  3. Which frequency should I use for timepoints? Each frame would be -I guess- overkill, rather I should save i.e. every nth frame and interpolate in between, which makes the storage questions in 2. even more difficult.




So is this idea even the right approach? If yes, how could I efficiently store and retrieve the data? Please note that I generally would like to go with using the data structure above, not deterministic gamestates and recording user input etc.


Thanks for any help!


EDIT: I realise I should describe the environment I use: Cocos2D for iPhone. There is a method update:(ccTime)delta. Ideally, this method would be called every 1/60 seconds, but there is no guarantee - delta is the actual time passed since the last gametick and could be a lot more or less than 1/60. It is in this method where I would like to store the current gamestate.



Answer





Doesn't that mean that search time for records matching a certain time will increase the longer the race is?



Nope :)


Say you store it as an array (note the snapshots are in chronological order, but not evenly spaced):


snapshots = [
{time: 0.0, position: {x,y,z}},
{time: 0.41, position: {x,y,z}},
{time: 0.57, position: {x,y,z}},
{time: 1.10, position: {x,y,z}},

{time: 1.67, position: {x,y,z}},
{time: 2.05, position: {x,y,z}},
{time: 3.24, position: {x,y,z}},
{time: 3.86, position: {x,y,z}},
{time: 3.91, position: {x,y,z}},
{time: 5.42, position: {x,y,z}},
...]

Then, when the replay/game starts, you get the first and second element from the array:


nextIdx = 1

previousSnapshot = snapshots[nextIdx-1]
nextSnapshot = snapshots[nextIdx]

Then in each frame (currentTime is the current time in this new game):


if currentTime > nextSnapshot.time
nextIdx++
previousSnapshot = snapshots[nextIdx-1]
nextSnapshot = snapshots[nextIdx]

# Do your magic here, e.g.:

snapshotPairGap = nextSnapshot.time - previousSnapshot.time
ratio = (currentTime - previousSnapshot.time) / snapshotPairGap
ghostPosition = {
x: previousSnapshot.position.x + ratio*(nextSnapshot.position.x - previousSnapshot.position.x)
y: previousSnapshot.position.y + ratio*(nextSnapshot.position.y - previousSnapshot.position.y)
z: previousSnapshot.position.z + ratio*(nextSnapshot.position.z - previousSnapshot.position.z)
}

Of course this could be optimized by caching some of the calculations. There's no searching through the array, just looking up specific indices.


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