Thursday, December 31, 2015

animation - smooth movement pygame


Hello im trying to learn more about smoother movement in games. I have created a little program to hopefully help me understand this. As far as i can tell i am suppose to track time, and update positions accordingly. However, for some reason, this concept is very hard for me to understand. I am using python and pygame at the moment for my games, and in none of them i have been able to come up with the smoothness i wanted. Ive also tried several games off of the pygame website and so far none of them have had the smoothness i prefer.


like i said, i understand you have to track time, and update positions accordingly instead of just +1'ing location each frame/iteration. By doing it the 'wrong way' as far as i understand then it doesnt neccesarily sync up with the monitor thus creating the sense of jittery motion, even at high FPS.


i have read a few articles on the subject of time steps, however i have been unable to fully understand the concept and incorporate it in my game. so i would like to ask, if someone can explain how to implement a timestep and create smooth motion. i am not going to incorporate physics in my first games, so the accuracy of the timer does not matter too much, what is most important right now is a game that can run as smooth as a proffesional game. i am sure a revisit if not simplified explanation of timestepping, and even how to do it in a simple way with python will be of benefit to any programmer hoping to use pygame/python for his games.



Anyway this is the program i was able to write, that doesent have smooth motion. Perhaps someone can modify it, so we can get a working example with time stepping and see how it improves the smoothness. PS. you need python 2.7 and a python 2.7 pygame compatible version to run the program/game


http://bpaste.net/show/qmE362O29sq6GPGBK3fg/



Answer



First we need to clarify what "smooth movement" is.


Let's first talk about smooth movement in a pixelated space.


Not taking into account motion blur and sub-pixel movement, the smoothest amount of movement you can have on a pixel screen is one pixel. So your code


pygame.draw.circle(SCREEN, (255, 255, 255), (newx, SCREENRECT.centery), 30)
pygame.display.update()
newx+= 1


actually procudes the smoothest movement in space possible.


Your code produces a smooth movement of roughly 60 pixels per second because of the clock.tick(60) call. This is smooth, but not very fast.


To get fast movement, you now could increase the amount of pixels your image jumps per step by using newx+= 2 or newx+= 5. But this, in line with the above definition, will no longer produce smooth movement. Why? Because you move more than 1px in one step, which we percieve as stuttering.


So, what can be done? If we want fast movement, but can only get it smooth by moving one pixel at a time, we need to move 1px at a time more often per second. And that means: increasing the renderings per second, or, more common, frames per second.


(Note that we have not yet talked about timesteps here at all.)


So as a first step, decrease the waiting time between frames (Clock.tick() essentially is a pause function with dynamic duration) by increasing the argument. Try clock.tick(120) or clock.tick(360).


At some point you will notice that the perceived speed of the motion does no longer increase. This is because you reach the limit of how long your rendering actually takes to compute. At this point, optimization has to happen if the movement is still to slow.


Your drawing routine is inefficient for various reasons:





  • It clears the whole screen to black every frame with SCREEN.fill((0, 0, 0)), although technically you would just neet to clear the area where the circle is.




  • You compute and draw a circle in every frame using pygame.draw.circle(). It would be more efficient to pre-render the circle to a surface an blit that surface to the background.




These would be starting points to get your simple animation smooth and fast. You can optimize further by abandoning Pygame Surfaces and switching to OpenGL. But it is important to note that there is always a limit to the speed of smooth, i.e. 1px movement. Most of the time the practical limit is the monitor refresh rate. If your monitor updates the application's display from the frame buffer memory, say, at 90 times per second (90 Hz), then 90 px / s is the most of smooth movement in space that you can get.


Now you were asking about timesteps, so let's talk about smooth movement in time.


We perceive an object moving smoothly if it moves by equal amounts of space in equal amounts of time. If you have tuned up the FPS in the above example to 360, you might have noticed that the circle stutters and moves irregularily. This is because at some frames Pygame manages to draw everything in less than 1/360 s, and in some frames not. This means that some times the circle does move 360px in one second, and some times the circle takes longer than one second wall clock time to move 360 px. This is because rendering time is not guaranteed. And this is where timesteps come in.


The principle of timestepping is to keep the movement in sync with the wall clock time. That means, instead of blindly moving a fixed amount of pixels per frame, you measure the time your frames take, and adjust the amount of movement (and possibly the time to pause) accordingly. The answer of Yos233 shows one way to do this using the return value of clock.tick().



Timestepping requires that there is a target speed of your animation. Say an object shall move 50 px per second. The basic procedure is




  1. Draw the object.




  2. Wait until 1/50 s has passed.




  3. Update position by 1 px.





  4. Repeat.




The critical point is when in 2. you see that actually more than 1/50 s has already passed. Here, to keep the movement smooth in time, you have to quantify how much time over 1/50 s has passed, and add to the amount of space to move accordingly.


Note that in this case you inevitably will have to move more than 1px to stay in sync; this means that your movement will be smooth in time, but no longer smooth in space.


To sum up:





  1. 1px movement is the smoothest you can get, and it is limited by the frame rate your whole setup can achieve.




  2. Timestepping will smooth out your movement over time, but will actually increase jumps and stutter if the target speed can not be met.




For further reading on timesteps, check out the excellent article Fix Your Timestep!.


phrasal verbs - What is the difference between "get through" and "go through"?


Is there any difference between "go through a door" and "get through a door"?



Answer




Get through means "to suffer through."
To get through something usually means in an emotional state, like to get through a divorce, or to get through something challenging, like a test.



She was so tired that it was difficult to get through the day.



Go through means "to pass through something."
"Go through something" is the physical of "go through something," and it is always in the present tense, like "go through a divorce" or "go through a tunnel."



After you buy your token, put it in the slot and go through the turnstile. Go through the old city gates and you will see beautiful 15th century church.




So its always you go through a door, not get through a door.


tilemap - Error rendering map android


I'm trying to read this text file and render the corresponding tiles on the screen.


trial map


The code for reading the map is as follows:


private void loadMap(InputStream is) throws IOException {

ArrayList lines = new ArrayList();
int width = 0;
int height = 0;

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;

}

if (!line.startsWith("!")) {
lines.add(line);
width = Math.max(width, line.length());
}
}
height = lines.size();

for (int j=0; j < 18; j++) {

String line = (String) lines.get(j);
for (int i=0; i < width; i++) {

if (i < line.length()) {
char ch = line.charAt(i);
Tile t = new Tile(i, j, Character.getNumericValue(ch));
tiles.add(t);
}
}
}


}

The first problem I have is with Character.getNumericValue(ch) as this does not seem to be doing anything, resulting in a NullPointerException. When I remove it and replace it with either a 1 or a 2 I'm able to render the tiles onto the screen but somehow the spaces in between the digits are interpreted as tiles, resulting in a continuous block of tiles eg in the second line with 1s results in tiles beginning from the left margin up until the last 1. How can I fix this?



Answer



If I have analyzed the problem correctly the issue here is that Character#getNumericValue(ch) is returning -1. This is because it is reading all characters in the line, including whitespace characters, which does not have a numeric value. The Character#getNumericValue(ch) javadocs read:



If the character does not have a numeric value, then -1 is returned.



The solution would be to do something like this inside of your for-loop where you create the tile:



// Inside of the for-loop...
if(i < line.length()) {
char ch = line.charAt(i);
int charValue = Character.getNumericValue(ch);

// Checks if the character is an invalid character such as a whitespace.
if (charValue == -1)
continue;

Tile t = new Tile(i, j, charValue);

tiles.add(t);
}

prepositions - Using "no" to emphasize a negative statement


We say something like



He is no ordinary human being.



This phrasing gives the negative more emphasis than usually given by negation device "not"



He is not an ordinary human being.




It is this added emphasis that I am trying to induce in the following sentence, but I have some doubts as to the usage of "no" after the verb "makes"



Her mastery of French makes her no typical member of the laity.



May I have some feedback on the sentence, please?


Thank you.


PS: And if the sentence is Ok, would the following sound better:



Her mastery of French makes of her no typical member of the laity.






How do I load a texture in OpenGL where the origin of the texture(0, 0) isn't in the bottom left?


When loading a texture in OpenGL, how do I specify the origin of the data I am loading?


For example, how would I load a Targa that has it's origin at the top left instead of the bottom left of the image?



Answer



You can't, at least not directly. The origin of textures in OpenGL is the lower-left corner. You need to vertically flip your image if it doesn't match this coordinate system. So it's really an image processing problem, not an OpenGL problem.


(Alternatively, you can flip all your texture coordinates that refer to the image.)


Wednesday, December 30, 2015

phrase meaning - "In the wake of"


I have a question about the usage of the phrase "in the wake of" here:




We are still in the wake of discriminatory laws against women and children.



I could not find a good dictionary definition that fits this usage of "in the wake of". But, the author of the sentence appears to be a non-native English speaker. Could the sentence, then, be poorly written?




c++ - 2D Platformer Collision Handling


I am trying to create a 2D platformer (Mario-type) game and I am some having some issues with handling collisions properly. I am writing this game in C++, using SDL for input, image loading, font loading, etcetera. I am also using OpenGL via the FreeGLUT library in conjunction with SDL to display graphics.


My method of collision detection is AABB (Axis-Aligned Bounding Box), which is really all I need to start with. What I need is an easy way to both detect which side the collision occurred on and handle the collisions properly. So, basically, if the player collides with the top of the platform, reposition him to the top; if there is a collision to the sides, reposition the player back to the side of the object; if there is a collision to the bottom, reposition the player under the platform.



I have tried many different ways of doing this, such as trying to find the penetration depth and repositioning the player backwards by the penetration depth. Sadly, nothing I've tried seems to work correctly. Player movement ends up being very glitchy and repositions the player when I don't want it to. Part of the reason is probably because I feel like this is something so simple but I'm over-thinking it.


If anyone thinks they can help, please take a look at the code below and help me try to improve on this if you can. I would like to refrain from using a library to handle this (as I want to learn on my own) or the something like the SAT (Separating Axis Theorem) if at all possible. Thank you in advance for your help!


void world1Level1CollisionDetection()
{
for(int i; i < blocks; i++)
{
if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==true)
{
de2dObj ballPrev;
ballPrev.coords[0] = ball.coords[0];

ballPrev.coords[1] = ball.coords[1];
ballPrev.coords[2] = ball.coords[2];
ballPrev.coords[3] = ball.coords[3];
ballPrev.coords[0] -= ball.xspeed;
ballPrev.coords[1] -= ball.yspeed;
ballPrev.coords[2] -= ball.xspeed;
ballPrev.coords[3] -= ball.yspeed;

int up = 0;
int left = 0;

int right = 0;
int down = 0;

if (ballPrev.coords[0] < block[i].coords[0] && ballPrev.coords[2] < block[i].coords[0] && (((ball.coords[1] < block[i].coords[1]) || (ball.coords[3] < ball.coords[1])) || ((ball.coords[1] < block[i].coords[3]) || ball.coords[3] < block[i].coords[3])))
{
left = 1;
}

if (ballPrev.coords[0] > block[i].coords[2] && ballPrev.coords[2] > block[i].coords[2] && (((ball.coords[1] < block[i].coords[1]) || (ball.coords[3] < ball.coords[1])) || ((ball.coords[1] < block[i].coords[3]) || (ball.coords[3] < block[i].coords[3]))))
{

right = 1;
}
if(ballPrev.coords[1] < block[i].coords[1] && block[i].coords[1] < ballPrev.coords[3] && ballPrev.coords[3] < block[i].coords[3])
{
up = 1;
}
if(block[i].coords[1] < ballPrev.coords[1] && ball
{
down = 1;
}


cout << left << ", " << right << ", " << up << ", " << down << ", " << endl;

if (left == 1)
{
ball.coords[0] = block[i].coords[0] - 18.0f;
ball.coords[2] = block[i].coords[0] - 2.0f;
}
else if (right == 1)
{

ball.coords[0] = block[i].coords[2] + 2.0f;
ball.coords[2] = block[i].coords[2] + 18.0f;
}
else if (down == 1)
{
ball.coords[1] = block[i].coords[3] + 4.0f;
ball.coords[3] = block[i].coords[3] + 20.0f;
}
else if (up == 1)
{

ball.yspeed = 0.0f;
ball.gravity = 0.0f;
ball.coords[1] = block[i].coords[1] - 17.0f;
ball.coords[3] = block[i].coords[1] - 1.0f;
}
}
if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==false)
{
ball.gravity = -0.5f;
}

}
}

To explain what some of this code means:


The blocks variable is basically an integer that is storing the amount of blocks, or platforms. I am checking all of the blocks using a for loop, and the number that the loop is currently on is represented by integer i. The coordinate system might seem a little weird, so that's worth explaining. coords[0] represents the x position (left) of the object (where it starts on the x axis). coords[1] represents the y position (top) of the object (where it starts on the y axis). coords[2] represents the width of the object plus coords[0] (right). coords[3] represents the height of the object plus coords[1] (bottom). de2dCheckCollision performs an AABB collision detection. Up is negative y and down is positive y, as it is in most games.


Hopefully I have provided enough information for someone to help me successfully. If there is something I left out that might be crucial, let me know and I'll provide the necessary information. Finally, for anyone who can help, providing code would be very helpful and much appreciated.


Thank you again for your help!


Edit: I have updated my code with a new algorithm that checks where the ball was previously before collision. Corner cases work on that single platform correctly now, but when I have a wall of objects, I keep can really slide against it, but if I move towards the wall while sliding, I pass through it and an essentially now standing on top of a block inside the wall. Also, there is a jittering effect that happens when I am on the ground, where the ball is constantly going up and down.



Answer



Thanks for all of the help, guys, and sorry for the late response.



I have taken all of these ideas into consideration, and they are helped me fix the issue. If anyone is curious to know how I solved the original and full problem, look here on Stack Overflow for the full answer (including explanations on handling collision more properly). The person who answered my question was really generous and provided a diagram, so that should help those who also have this problem.


Thanks to the following people for helping me with this problem:



  • DanTup - Danny Tuppeny

  • bummzack

  • ghostonline

  • ultifinitus


I appreciate it very much!


conditionals - Need answer to an "if" question


I had a test today and there was this question : If you are a well-organized person, you .... your time.


a) will manage b) manage



I'd like to know the answer and why?


Thanks in advance.




distribution - How do you create a single/internal pre-loader for a Flash game written using Flex?


I've got a somewhat large SWF which I'd like to deliver through a pre-loader so the user doesn't have to appear to wait as long. With Actionscript it's pretty easy to create an external pre-loader but doing so makes it harder to distribute my game. What methods are available for including the pre-loader in a single SWF?



Answer



If you're using Flex in your project, i.e. you created a Flex project, including a preloader in your Application is very easy: set a class name in you Application declaration:




Now, create a class called com.example.Preloader which extends Sprite, and implements mx.preloaders.IPreloaderDisplay.



Basically, any Sprite can be a preloader display, provided that implements the functions written in the IPreloaderDisplay interface. These functions are properties that the application pass to the class so it can know something about the application: height, width, background color, and two important functions: a "preloader" property setter, and a initialize function.


The preloader property setter accepts a Sprite, and you usually add listeners to the parameter given to you, to the PROGRESS, and COMPLETE events that the sprite dispatches to let the preloader know how is the loading going. This is an example of the property setter:


public function set preloader(value:Sprite):void
{
_preloader = value;

value.addEventListener(ProgressEvent.PROGRESS, progressHandler);
value.addEventListener(Event.COMPLETE, completeHandler);

value.addEventListener(RSLEvent.RSL_PROGRESS, rslProgressHandler);

value.addEventListener(RSLEvent.RSL_COMPLETE, rslCompleteHandler);
value.addEventListener(RSLEvent.RSL_ERROR, rslErrorHandler);

value.addEventListener(FlexEvent.INIT_PROGRESS, initProgressHandler);
value.addEventListener(FlexEvent.INIT_COMPLETE, initCompleteHandler);
}

The initialize function is called by the application when it starts loading the real data. The default preloader uses this function to start a timer, which after some time has passed and the application is still loading, it actually displays the preloader (this is to prevent the preloader to appear immediately, until the user has waited too much time for the app to load)


    public function initialize():void
{

_startTime = getTimer(); //from flash.utils.getTimer()
}

You might want to download some real source code, though, so I recommend this article which answers some other preloader details on how to draw things inside it: http://iamjosh.wordpress.com/2007/12/18/flex-custom-preloader/


I said at the beginning that this was very easy, but if you're a newcomer you might find this rather daunting. But once you learn how to do it, you'll find that all preloaders in Flex work the same.


collision detection - How do I make good guy attacks only hit bad guys and vice versa?


My game has many different type of good guys and many different type of bad guys. They will all be firing projectiles at each other but I don't want any accidental collateral damage to occur for either alignment. So bad guys should not be able to hit/damage other bad guys and good guys should not be able to hit/damage other good guys.


The way I'm thinking of solving this is by making it so that the Unit instance (this is javascript, btw), has an alignment property that can be either good or bad. And I'll only let collision happen if the


class Attack

boolean didAttackCollideWithTarget(target)
return attack.source.alignment != target.alignment and collisionDetected(attack.source, target)


This is pseudo-code, of course.


But I'm asking this question because I get the sense that there might be a much more elegant way to design this besides adding yet another property to my Unit class.



Answer



Collision Filtering


A more robust situation that scales into many layers is to use filtering, which is not the same thing as grouping.


This works best by giving every object 2 bitmasks.


Category
Mask

And only trigger a collision if the below is true.



(filterA.maskBits & filterB.categoryBits) != 0 &&
(filterA.categoryBits & filterB.maskBits) != 0;

Its easiest to default the Mask to 0xFFFF which results in it colliding with everything. And default the Category to 0x0001. objects collide with the categories in the others mask will there be a collision.


Another way to think of it is each object has a type and a list of all the types it can collide with. Only when two objects both collide with the types of each other is there a collision. You could have the same behavior having a list of enums instead of a mask but a mask in an order of magnitude faster.


Scenario you describe


I like to take advantage of enums in this situation.


So say we have.


enum Categories {
GoodGuy = 0x0001,

BadGuy = 0x0002,
Bullet = 0x0004,
GlassWall = 0x0008,
Lazer = 0x0010,
All = 0xFFFF
};

Bullet shot by a good guy


 Category = Bullet
Mask = BadGuy | GlassWall


Good Guys


 Category = GoodGuy
Mask = All

Bad Guys


 Category = BadGuy
Mask = All

Which results in the below when a Bullet shot by a good guy hits another good guy.



(All & GoodGuy) != 0 && <-- Passes
(GoodGuy & (BadGuy | GlassWall)) != 0; <-- This would fail

But it will hit bad guys.


(All & BadGuy) != 0 && <- Passes
(BadGuy & (BadGuy | GlassWall)) != 0; <-- Passes

Tuesday, December 29, 2015

architecture - How often to update a Game Client about the World?



Using socket.io, I have a communication similar to that of other MMORPGs, a steady connection with messages.


In my design so far, the client sends the player's position and animation frame with every update frame. When the server gets that message, it broadcasts it to all the clients, which will then move the graphic accordingly.


Would it be a better idea to 'collect' these and broadcast them, say, once in 1/10 of a second?


Also, should the client send many different messages (exp gained, clicked on item) as soon as they occur or rather just one collected? The first would be implemented easier.



Answer



I am going to approach this from a high-level discussion and then work towards your questions. For the sake of disclosure, I have no personal experiencing using socket.io but a lot of exposure to the problem space with regards to MMORPGs.


The design of an MMORPGs engine's network architecture and/or the selection of a middle-ware or open source project to provide the functionality is one of the more challenging decisions influenced by the game design, budget and technical expertise of the team. The ultimate choice will influence other architectural decisions (and sometimes design decisions as well).


As developers of MMORPGs, we plan for great success (often also known as catastrophic success) where large numbers trigger warning lights and sirens. One of the scary large numbers that crops up is in algorithms that are N-squared (N^2 hereafter), in your question the first thing that jumped out to me is that it sounded like the design called for an entity to broadcast information to all other connected entities. This is the classic example of an N^2 problem.


MMOs generally approach addressing N^2 issues by attacking the problem in several different ways; awareness systems (situational, spatial, etc) where an entity is aware of some subset of all of the other entities, partitioning players into different "shards", partitioning players in "zones" and/or instancing, implementing game mechanics that discourage too many players from congregating together (Asheron Call's teleport storms), etc.


Most MMORPGs and many FPS engines have fairly sophisticated networking architectures that support a variety of features including:




  • reliable and unreliable communication pathways (TCP, custom implementations of reliable UDP and UDP packets)

  • bandwidth shaping (prioritization, lifetimes, etc)

  • automatic replication of field/viarable data and function calls

  • atomic sets of data (i.e. data that is communicated together)

  • discrete updates (i.e. where every transition is important)

  • latency correction

  • a variety of tricks to make the client feel responsive


I find that the Unreal Networking Documentation and Valve Networking Documentation provide a good primer on a variety of the issues.



So, now lets approach the questions.



Would it be a better idea to 'collect' these and broadcast them, say, once in 1/10 of a second?



It's hard to provide a simple yes or no answer here...because it depends on the scale (number of observing entities), frequency of updates and size of updates. For example, collecting them all might be horridly wrong if the size of the updates could blow a buffer somewhere.


The client for MMORPGs and FPS games are generally designed such that they will visualize something that "looks" right even if they do not receive an update for many more update frames than is "normal". When using unreliable communication (UDP) you can just expect to lose some number of updates into the void, clients can make up for this by sending more frequent updates than might be used with a reliable transport.


From a cursory review of the socket.io documentation, it looks like it supports both reliable and unreliable (volatile in its terminology) communication pathways.


I'd approach this first by tackling, at what frequency are updates needed...


If a player is moving in a straight-line at a constant rate, a lower update frequency is fine because the observing clients can predict with high accuracy where the player will be at any point in time. When a player is turning in a tight circle or making rapid direction changes, then much more frequent updates are required. Conversely, when a player is not moving at all there is no reason to send out movement updates at all.


No matter what, is probably not (generally) necessary to send updates every frame from the client to the server. The server itself may choose to send messages each frame where it has them, or delay them (see bandwidth shaping, prioritization and update lifetime).



Other types of updates have different characteristics...for example consider a "health" field that is modified when a player or creature is damaged. One way to implement this is broadcast each change immediately when it happens, but this leads to wasting processing and bandwidth if the value is changed multiple times in a frame or consecutive frames (networking architectures that implement bandwidth shaping solve this issue by coalesing the updates to only the most recent is sent to an observing client when they have available bandwidth).



should the client send many different messages (exp gained, clicked on item) as soon as they occur or rather just one collected?



Again, no simple yes or no answer is going to work here. Depending on what precisely you mean by collected...both may be right under different circumstances and also depend on implementation of the networking layer.


Collecting messages for a specific entity to be sent as one message can (depending on implementation) reduce the bandwidth overhead for sending a message (reducing your costs) conversely (depending on implementation, such as field/value mappings communicated by strings) can increase bandwidth requirements compared to a simpler specific message type.


Reviewing the socket.io documentation, it would appear to me that message overhead is on the higher end of the spectrum which would favor collecting updates to send as an aggregate message as opposed to lots of single updates.


I'd recommend reviewing all of the updates you contemplate replicating, for example most MMORPGs and FPSs do not bother to send player clicked on X events to observing clients unless that would result in a state change for an object of which they were aware as well.


Monday, December 28, 2015

pronouns - Using "it" at the beginning of a sentence



It can be difficult to talk about subjects like XXXX.





It can be difficult to learn a new language.




I hope it doesn't rain Today.



What does it means in the above sentences?
Why should we start the sentences with it?



Answer



It in those sentences is called dummy pronoun: It is used without any reference to any agent, but it is syntactically required.



The first sentence could be rephrased as "Talking about subjects like XXXX can be difficult." while the second sentence could be rephrased as "Learning a new language can be difficult." The difference between the original sentences and the one I am suggesting is the word order. With the original sentences, the first words are "It can be difficult"; that could be done to put those words in evidence.


With sentences about weather, the verb (e.g. rain, snow) is impersonal, and intransitive. Since in English the subject of a sentence is normally not implicit, it is used. (In English you don't normally write a sentence like "Is playing football with his friends." or "Rains.")


3d - OpenGL ES 2.0 Point Sprites Size


I am trying to draw point sprites in OpenGL ES 2.0, but all my points end up with a size of 1 pixel...even when I set gl_PointSize to a high value in my vertex shader.


How can I make my point sprites bigger?



Answer



OpenGL ES 2.0 supports Point Sprites; i use them for particles. Just use glDrawElements with GL_POINTS.


In vertex shader, you set the size with gl_PointSize and use gl_PointCoord in fragment shader for texture mapping.


My vertex shader:


uniform mat4 uMvp;

uniform float uThickness;

attribute vec3 aPosition;
attribute vec2 aTexCoord;
attribute vec4 aColor;

varying vec4 vColor;

void main() {
vec4 position = uMvp * vec4(aPosition.xyz, 1.);

vColor = aColor;
gl_PointSize = uThickness;
gl_Position = position;
}

My fragment shader:


uniform sampler2D tex0;
varying vec4 vColor;

void main()

{
gl_FragColor = texture2D(tex0, gl_PointCoord) * vColor;
}

If you are on Android, you can look my french Tutorial. There is a full project with point sprites.


definite article - Is the "the ... the ..." construction governed by some grammatical rule?



a) The more I study, the less I learn.


b) More I study, less I learn.



Could we rewrite the sentence shown under the letter a) in the form shown under the letter b) without breaking any grammatical rule? If not, why not?



Answer



This construction is an idiom which is not governed by any general grammatical rule, but is in effect a rule all by itself. Its structure is



The [x-ER], the [x-ER]




where the two [x-ER]s are parallel expressions in the comparative grade.



The [more], the [merrier]



[x-ER] need not be a simple adjective; it can be a more complex (or compound) phrase or full clause, with the comparative fronted:



The [higher they rise], the [harder they fall]
The [more effort I put into something I care about], the [more satisfaction I get out of it]




But the thes are essential components; they cannot ordinarily be omitted. To be sure, you may hear someone drop them in speech, under the pressure of strong emotion (real or simulated):



Crap. Harder I work, less I get done. Crap.



But that should not be done in writing, unless what you're writing is dialogue.




HISTORICAL NOTE:
As this explains, the thes in this expression aren't the ordinary definite article but ‘worn-down’ forms of an Old English pronoun — which is why the ordinary rules don’t apply.

word request - What do you call someone who has a lot of power and keeps a big secret?


I need help for a name of an essay for a school project.


What do you call someone who has a lot of power in maintaining order in a country and keeps a big secret that affects everyone but doesn't want to say it in fear he will lose his position. I need a noun.



Answer



Depending on the details, perhaps:



  • A conspirator (someone conspiring in secret, often to seize or keep power)

  • A fraud (someone who deceives others, perhaps about their own credentials)


  • A schemer

  • A plotter

  • A despot (someone with absolute, unlimited power)

  • An imposter (someone who ought not be in the position they are in, perhaps by pretending to be someone they are not)


unity - A coroutine to rotate one point around another by a given angle without referring to game object


I need to rotate a point around another point (in 2D) by a given angle over a given duration, independent of game object (meaning that I've manually created the points and they're not positions from a game objects transform ) as shown in the image below where point B rotates to C by and angle e around A by with radius AB. Using a coroutine would be preferable.



UPDATE


Based on links provided by @MichaelHouse I wrote the following methods to rotate a control point over time by a certain angle but it rather moves to a point (which is not the desired point) immediately to another point, not by the right angle. I'm not sure what I've done wrong.


public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle)
{
return angle * (point - pivot) + pivot;
}

IEnumerator RotateControlPointWithDuration(Vector3 point, Vector3 pivot, float duration, float angle) {
float currentTime = 0.0f;
float ourTimeDelta = 0;


ourTimeDelta = Time.deltaTime;
float angleDelta = angle / duration; //how many degress to rotate in one second

while (currentTime < duration)
{
currentTime += Time.deltaTime;
ourTimeDelta = Time.deltaTime;

Vector3 newPos = RotatePointAroundPivot(point, pivot, Quaternion.Euler(0, 0, angleDelta * ourTimeDelta));

points[0] = new Vector2(newPos.x, newPos.y);

yield return null;
}
}

IEnumerator runMovement() {

yield return new WaitForSeconds(2.0f);
Vector3 point = new Vector3(points[0].x, points[0].y, 0);

Vector3 pivot = new Vector3(points[3].x, points[3].y, 0);
StartCoroutine(RotateControlPointWithDuration(point, pivot, 2.0f, 45.0f));
}

enter image description here


UPDATE 2


I've tried another approach using trig functions, but the point moves erratically before finally arriving at a point that seems to be the right point. Please see the code below:


 IEnumerator runMovement()  {

yield return new WaitForSeconds(2.0f);

Vector2 pivot = points[3];

StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f));

}

IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle)
{
float currentTime = 0.0f;
float ourTimeDelta = 0;

Vector2 startPos = points[0];

ourTimeDelta = Time.deltaTime;
float angleDelta = angle / duration; //how many degress to rotate in one second

while (currentTime < duration)
{
currentTime += Time.deltaTime;
ourTimeDelta = Time.deltaTime;


points[0] = new Vector2(Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) - Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.x,
Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) + Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.y);

yield return null;
}
}

Answer



Your first "Update" code is mostly right, but it's using the wrong time delta.


Since "delta" just means difference, we shouldn't automatically reach for any old time variable with "delta" in the name, but instead consider which two endpoints we want a difference between.


Here the delta taken by the quaternion constructor wants the time difference between now and the start of the animation, so it can construct a rotation accounting for the full arc that should have been traversed over that interval. But Time.deltaTime gives you the difference between this frame and the previous frame - this will always hover close to your framerate (eg. 33 or 17 ms), rather than progressing smoothly from zero to your full duration.



So, we can correct and simplify the code a bit like this:


IEnumerator RotatePointAroundPivot(Vector3 pivot, float angle, float duration) {

Vector3 startPoint = points[0];

float progress = 0f;
float rate = 1f/duration;

while(progress < 1f) {
progress += Time.deltaTime * rate;

Quaternion rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Min(progress, 1f))

// If your output is a Vector2, this will implicitly omit the z.
points[0] = pivot + (rotation * (startPoint - pivot));

yield return null;
}
}

Now we have a progress variable that increases from zero to one over our duration, and we can use this to blend the angle from zero up to the full desired arc.



Sunday, December 27, 2015

present perfect - Difference between: "it has rained / been raining for two hours"




​I read that this is the difference between present perfect and present perfect continuous.



A1: It has been raining for two hours [and I don't expect it to stop soon].
A2: It has rained for two hours [and will likely continue to do so in the future].



Source: 'It has rained for two hours.' Is it raining now? or It stoped raining now?


Is it right? I knew it another way.
Could you please tell me what is right?




possessives - Genitive Saxon: Do you append apostrophe s ('s) after plurals and words ending with s?


Should the apostrophe and the s of genitive Saxon be used after plural forms or words ending with the letter s? For example:



airplanes wings must be defrosted before taking off



or



airplanes's wings must be defrosted before taking off





grammar - "It works" vs "It is working"



The photocopier broke down yesterday, but now it's OK.



a) It is working again. It has been repaired.


b) It works again. It has been repaired.



What is the difference in meaning between those two ways of saying. I'm interested in all the subtleties.



Answer



This is intuition and not based on something I have read.




  1. In fact these sentences are quite similar and native speakers could and would use them both to describe a photocopier that wasn't working yesterday and is working today.





  2. Using the verb "works" (in the sense of "functions," not in the sense of "labors") I would be more likely to use the progressive for something that isn't in a state of "not-working" for too long.




e.g. My typewriter from high school still works! The photocopier is working again! At long last, democracy works again! Is the drink machine working? (I want to buy a Coke right now.) Does the drink machine work? (I've never seen anyone use it, it just sits there, is it even functional?)


But again these distinctions are quite subtle and other native speakers may disagree with me.


c# - Generate random numbers without repetitions


How to generate Random numbers without repeating any numbers in the given target like(1-5000) there should be no reparation and I should be able to get 5000 randomized numbers. I should be able to run the randomized as many times as the user wants,How to do with C#


For Sample Target is (1-10) No of times to run =2


First run: 5,4,6,8,3,1,2,0,7,10


second run 6,3,5,8,4,2,0,1,10,7


Like this I should be able to get the results as many times as I run..



Answer



As others have pointed out, what you're looking for is effectively a shuffled deck of cards. Every card (in this case, a unique number) is present exactly once, in a randomized order. By drawing cards from the deck one at a time, you create a psuedorandom number string with no repeats.


(Obviously, once you've exhausted the deck, you'll need to either reuse it or reshuffle it to generate the next number)


A fast way to do this is with a Fisher-Yates shuffle, also commonly called a Knuth Shuffle:



// Prepare a deck of sequential numbers from min to max:

int count = max - min + 1
int[] deck = new int[count];

for(int i = 0; i < count; i++)
{
deck[i] = min + i;
}



// Shuffle it:

for(int i = count - 1; i > 1; i--)
{
// Pick an entry no later in the deck, or i itself.
int j = Random.Range(0, i + 1);

// Swap the order of the two entries.
int swap = deck[i];

deck[i] = deck[j];
deck[j] = swap;
}

// Now deck[] contains all numbers from min to max
// in a random order with no duplicates.

This can also be combined into one pass:


int count = max - min + 1;
int[] deck = new int[count];


for(int i = 0; i < count; i++)
{
int j = Random.Range(0, i + 1);

deck[i] = deck[j];
deck[j] = min + i;
}

One neat trick is that you don't even have to shuffle all at once for this. You can randomize as you go, at a constant cost per card drawn:



[System.Serializable]
public class Deck {
[SerializeField]
T[] deck;

// Tracks a partition between the deck & discard pile.
// All entries at i < remaining are in the undrawn deck,
// remaining <= i < deck.Length are in the discard pile.
int remaining = 0;


public T Draw() {
// If we ran out of cards, shuffle the discards to make a new deck.
if(remaining == 0)
remaining = deck.Length;

// Pick a card at random from the remaining deck.
int chosenIndex = Random.Range(0, remaining);
T chosenItem = deck[chosenIndex];

// Remove the card from the remaining deck and place it at the

// top of the growing discard pile.
remaining--;
deck[chosenIndex] = deck[remaining];
deck[remaining] = chosenItem;

return chosenItem;
}
}

Saturday, December 26, 2015

algorithm - Is A* efficient even when the obstacles are moving?


I'm just starting to learn about path-finding and have been looking into the A* algorithm and my main concern is that it all of the examples I have seen show static obstacles that it computes around.


If I have moving obstacles, say other characters for example, moving around as well that the character must find their way around, I'm assuming I'll have to run the algorithm each frame, but I'm worried that will become rather expensive for the hardware to process each frame for each moving actor.



So is A* still efficient enough to use whenever the obstacles are moving too, or is there another method of path-finding that handles moving obstacles more eloquently?



Answer



There are multiple algorithms that are much faster than A* when you need to recalculate a path with moving obstacles. See here under "Simple Recalculations".


However, you're not likely going to find an off-the-shelf solution for any of them, so in 99% of cases they're overkill for a game. Your time would be better-spent using an existing, fully-optimized A* solution, and using the common existing tricks for speeding up pathfinding in games:



  • Only recalculating the best path in infrequent intervals

  • Sharing best-paths among multiple units (example)

  • Creating a hierarchical graph so you only need to recalculate part of the path


etc. You can find more info about these tricks and more all over this site, or on Amit's A* pages



future tense - "is getting" vs "will get"


Are there difference between those sentences?




  1. Alex is getting married next month.

  2. Alex will get married next month.




Seems that the first one is expressed in present continues, and the second on in future tense. Am I correct?



Answer



The present continuous/progressive construct can be used to refer to a future event, typically a near-future event, especially if qualified with a time expression.



I'm going to the park tomorrow.


I'm leaving this job in two weeks.


She's testing the device next year.



There's little difference in meaning if a time expression is used. If a time expression is not used or able to be pulled from context, it could be confused with an actual continuous or progressive meaning.




John will get married. (We don't know when but we know he plans to get married. He's not in the process of doing that now, though.)


John is getting married. (He is either planning to get married or midway in the process of getting married. This is ambiguous unless context provides information.)



auxiliary verbs - Why do we use "have" with does and not "has"?


Does and has both are used with singular pronouns (He has the bottle , He does play cricket , etc) whereas Do and have are used with plural pronouns ( They have the bottle , Do they like cricket? , etc)


But still we use Does with have ( She does have a car ). Why? Shouldn't it be




She does has a car.




Answer



You need to realize that a verb can be either



  • finite (= matches the number of the subject of the sentence) or

  • nonfinite (= no inflection), which are infinitive, participles and gerunds. We are dealing with infinitives in your examples.


For an independent clause (AKA "sentence") you need at least one finite verb and unless you are making a "list" ("She laughs and sings and dances.") you use only one finite verb. In your example sentences you use four finite verbs, do, play, like and have.



Very simple sentences use only one verb, which by definition must be finite.:



He has the bottle.
They have the bottle



For questions or special emphasis you use an auxiliary verb (-> finite) together with a verb in the infinitive:



He does play cricket.
Do they like cricket?




So yes, in these cases "do" becomes "does" for third person singular because it is finite.


rotation - How to implement friction in a physics engine based on "Advanced Character Physics"


I have implemented a physics engine based on the concepts in the classic text Advanced Character Physics by Thomas Jakobsen. Friction is only discussed very briefly in the article and Jakobsen himself notes how "other and better friction models than this could and should be implemented."


Generally how could one implement a believable friction model on top of the concepts from the mentioned article? And how could the found friction be translated into rotation on a circle?




I do not want this question to be about my specific implementation but about how to combine Jakobsens ideas with a great friction system more generally. But here is a live demo showing the current state of my engine which does not handle friction in any way: http://jsfiddle.net/Z7ECB/embedded/result/




Below is a picture showing and example on how collision detection could work in an engine based in the paper. In the Verlet integration the current and previous position is always stored. Based on these a new position is calculated. In every frame I calculate the distance between the circles and the lines. If this distance is less than a circles radius a collision has occurred and the circle is projected perpendicular out of the offending line according to the size of the overlap (offset on the picture).


Velocity is implicit due to Verlet integration so changing position also changes the velocity. What I need to do know is to somehow determine the amount of friction on the circle and move it backwards parallel to the line in order to reduce its speed. picure showing how collision occurs



Answer




You should take a look at Mathias Mueller et all's "position based dynamics" paper. It's basically the same as Jacobsons' paper and he might give you more info about friction.


http://www.matthiasmueller.info/publications/posBasedDyn.pdf


They state that friction is basically damping the particle's velocity in the plane of the collision by some scalar value.


Note that this doesn't give you any coulomb friction effects (the amount of momentum into the collision doesn't affect the magnitude of the friction force) but you might be able to get that by considering the particle's velocity into the collision plane.


Friday, December 25, 2015

Question regarding meaning of “spell out”




There was an unearthly quality to the atmosphere inside the Frieze New York art fair, like the air in a plane—still but pressurized, with an unsettling hum—when the fiction writer Ottessa Moshfegh visited to speak about her work one afternoon in May. “I hate this fair already,” she said when she walked in, handing her ticket to a very tall, very pale man dressed entirely in black lace. Almost immediately, she was lost in the labyrinth of works for sale: Takashi Murakami’s lurid blond plastic milkmaids with long legs and erect nipples; the words “any messages?” spelled out in neon tubing. It was like an enactment of the world inhabited by the protagonist of Moshfegh’s forthcoming novel, “My Year of Rest and Relaxation,” who works at a gallery in Chelsea, amid objects like a quarter-million-dollar “pair of toy monkeys made using human pubic hair,” with camera penises poking out from their fur. “Did I do this?” Moshfegh said, only half kidding. She sometimes gets the sense that she has the power to conjure reality through her writing.



Firstly Who is saying this sentence? The writer of this text? Or Moshfegh? (I did not think so) or a vague voice from neon tubing?


Secondly spell out is different form spell? Does it mean a n y m a s s a g e s ?


Spelling alphabet by robot inside the tube?


Thirdly, is there any connection between this and the next sentence when it is talking about “enactment” If yes can you paraphrase it please?





past tense - "When is the last time...?" OR "When was the last time...?"


I usually say "When was the last time...?", but I came across this conversation. So I wonder which one is correct: is, was or either.



Henry: I was on the phone for an hour.
Ron: Who were you talking to for an hour?
Henry: Sam, an old friend from college.
Ron: When is the last time you talked to him?
Henry: At college graduation!
Ron: Wow! That was 30 years ago!
Henry: We had a lot of catching up to do.


Source: http://www.talkenglish.com/conversation/practice/catching-up-with-a-friend



Answer



Both are correct, although there's a bit of room for discussion.



The last time you spoke to him is obviously in the past, but it is in the past now. So when is the last time is correct.


However, the last time you spoke to him was a time before now. Therefore, When was the last time is also correct.


When was the last time is presently used much more often, as this nGram view shows. Interestingly, neither shows up much before 1960, when what was the last time was more popular, and what is the last time was non-existent.


phrase usage - "need + verb-ing" vs "need + [to be] + verb-ed"



1 That sofa needs cleaning again.


2 That sofa needs to be cleaned again.




Which of the above senteces sounds more natural? And, is "to be" always needed in structures like 2, as, for example, in:



2/a You need your head examined.


2/b You need your head to be examined.





ellipsis - Omitting a repeated verb


What is the rule and meaning of does in the following sentence (I think the appear omitted by it but if I am wrong please correct the title and tag):



The Moon illusion is an optical illusion which causes the Moon to appear larger near the horizon than it does higher up in the sky. (https://en.wikipedia.org/wiki/Moon_illusion)



MORE EXAMPLES




  1. Sound travels faster in liquids and non-porous solids than it does in air (https://en.wikipedia.org/wiki/Speed_of_sound).

  2. This makes it possible for the Sun to rotate faster at its equator (about 25 days) than it does at more extreme latitudes (about 35 days near its poles) (https://en.wikipedia.org/wiki/Sun).

  3. The Sun appears larger at sunrise than it does while higher in the sky, in a manner similar to the moon illusion (https://en.wikipedia.org/wiki/Sunrise).



Answer



It's an interesting question. The facts seem simple enough:


The author is saying does instead of appears because they don't want to repeat themselves.


But you can come up with more than one theory to explain those facts:





  1. In English, an auxiliary verb like do lets us omit the rest of a verb phrase:



    Do you like ice cream?
    Yes, I like ice cream.



    or



    Do you like ice cream?
    Yes, I do like ice cream.




    Adding the auxiliary verb do lets us omit the rest. This is called Post Auxiliary Ellipsis.


    In my example, you could also say:



    Yes, I do like ice cream.



    That is, you can add do without omitting the rest. The ellipsis is optional.


    Do is appropriate without omission in this example because of the emphasis on whether the clause is true or not. This is often the case in response to a yes-no question. But in your example, things are a little different:



    The Moon illusion is an optical illusion which causes the Moon to appear larger near the horizon than it appears higher up in the sky.


    The Moon illusion is an optical illusion which causes the Moon to appear larger near the horizon than it does appear higher up in the sky.




    We can replace appear with does and it sounds fine. But if we add does without omitting appear, it sounds weird:



    The Moon illusion is an optical illusion which causes the Moon to appear larger near the horizon than it does appear higher up in the sky.



    I've marked this example with a symbol to indicate that it's questionable. In this case, adding emphasis on whether the clause is true or not is very strange―we're not answering a yes-no question, we're in the middle of a comparative construction ("X-er than" / "more X than"). Adding does here makes the sentence strange and hard to understand.


    By the way, remember that I called this Post Auxiliary Ellipsis, and not Post-do Ellipsis? That's because any auxiliary works, not just do:



    Are you going to the store?
    Yes, I am going to the store.




    In this example, we already have the auxiliary be, so we use that one instead of adding do.




  2. Of course, we could come up with another theory to explain the same facts. What if we wanted to keep things as simple as possible?



    The Moon illusion is an optical illusion which causes the Moon to appear larger near the horizon than it appears higher up in the sky.


    The Moon illusion is an optical illusion which causes the Moon to appear larger near the horizon than it does higher up in the sky.



    We could just say does replaces appears. If we do that, we're calling do a pro-verb. A pro-verb is like a pronoun, except it substitutes for verbs (or verb phrases) instead of nouns. And in English, do is our pro-verb of choice.



    This explanation works pretty well, as long as we're willing to admit other auxiliaries as pro-verbs:



    Are you going to the store?
    Yes, I am.



    Now auxiliary be is a pro-verb substituting for the entire verb phrase be going to the store, at least according to the pro-verb theory.




So there's probably more than one way to answer your question. These are just a couple ways of thinking about it.


algorithm - How to get a smooth path for a vehicle in a 2D top down map?


I am making a 2D tile based game which involves having AI that needs to traverse the map avoiding obstacles in a natural and smooth path (NOT NECESSARY THE SHORTEST)



The orientation of the vehicle is also important in the example above the initial orientation of the vehicle is to NORTH but the orientation of the vehicle at the destination doesn't matter.


All I could do now is to compute the path using A* or a BFS fill through the center of the tiles.


This is an example of a desired path:


Desired Path




Thursday, December 24, 2015

optimization - Effecient tilemap rendering


I have done mostly tile based games, but never really bothered with optimization. I always just rendered all the tiles that convered the viewport. I am currently working on platformer for a mobile device, which has some performance issues, ecspecially when using multiple layers of tiles.


Most tiles are pretty static without animations. I wouldn't really have to render them each frame. The clear() -> draw() loop is really printed into my brain, I'm having a hard time thinking how the handle rendering without clearing the screen each frame.


I'm currently doing this: - start game, render screen once - Once a tile changes, save this in a "tile_changed" array - Each frame, re-render all the changed tiles and clear the array


This works pretty fine, and there is a notable boos in performance. However, there are a view issues - The PlayN framework offers no way to "erase" drawn items. Whenever I want to erase a single tile I have to completely clear the screen and redraw every tile. (PlayN SurfaceLayer). I'm using a scroll background, so can't just fill an empty tile with the background color. I can imagine low level libraries like opengl having this same issue, do they use some sort of workaround for this?




  • I'm not sure how to recognize when new tiles come into the screen whenever the camera moves. I would normally just render the tiles in view each frame, so this never posed a problem.





  • I have no idea if having such a big drawn rendertarget in memory is a good idea. The player could have walked across a huge map and have thousands of tiles drawn. Should I worry about this?




Any other optimiztions that I'm missing are appreciated.




The awnsers note that most engines draw all tiles every frame. But I know that on some less powerfull platforms this is not the case. I believe flashpunk is using some sort of buffer that only draws new tiles when you make changes in the grid. Unfortunately this is not possible for me because I have no way of clearing a single tile without clearing the entire buffer.


I'm looking into optimazations like this, which enable me to have a very large amount of tiles on the screen.




Unity Shader Graph, set blackboard properties from code


I have a Shader Graph shader with a blackboard property that I want to change from within my code. The property is called Highlight here are the things I have tried:


Color myColor = new Color(1f,0,0,1f);
material.Color = myColor; // throws error (as I expected)
material.SetVector("Highlight", myColor); // Name in blackboard window

material.SetVector("HighlightColour", myColor); // Name in material property
material.SetVector("Color_8C3A526", myColor); // Name in the shader inspector

None of these work.


Here's the shader set up: The Unity Shader Graph showing a fresnel shader with a Highlight property in the blackboard




past tense - "I heard the clock strike ten": why not "striked ten"?



I heard the clock strike ten.



Why is strike in the simple present in this sentence?


What are the conditions for using a simple present verb after a past tense verb to talk about the past?




3d - How to programatically retarget animations from one skeleton to another?



I'm trying to write code to transfer animations that were designed for one skeleton to look correct on another skeleton. The source animations consist only of rotations except for translations on the root (they're the mocap animations from the CMU motion capture database). Many 3D applications (eg Maya) have this facility built-in, but I'm trying to write a (very simple) version of it for my game.


I've done some work on bone mapping, and because the skeletons are hierarchically similar (bipeds), I can do 1:1 bone mapping for everything but the spine (can work on that later). The problem, however, is that the base skeleton/bind poses are different, and the bones are different scales (shorter/longer), so if I just copy the rotation straight over it looks very strange.


I've attempted a number of things similar to lorancou's solution below to no avail (ie multiplying each frame in the animation by a bone-specific multiplier). If anyone has any resources on stuff like this (papers, source code, etc), that would be really helpful.



Answer



The problem was one of numerical stability. Approx 30 hours of work on this over the course of 2 months, only to figure out I was doing it right from the very start. When I ortho-normalized the rotation matrices before plugging them into the retarget code, the simple solution of multiplying source * inverse(target) worked perfectly. Of course, there's a lot more to retargeting than that (in particular, taking into account the different shapes of the skeleton, ie shoulder width, etc). Here's the code I'm using for the simple, naieve approach, if anyone is curious:


    public static SkeletalAnimation retarget(SkeletalAnimation animation, Skeleton target, string boneMapFilePath)
{
if(animation == null) throw new ArgumentNullException("animation");
if(target == null) throw new ArgumentNullException("target");


Skeleton source = animation.skeleton;
if(source == target) return animation;

int nSourceBones = source.count;
int nTargetBones = target.count;
int nFrames = animation.nFrames;
AnimationData[] sourceData = animation.data;
Matrix[] sourceTransforms = new Matrix[nSourceBones];
Matrix[] targetTransforms = new Matrix[nTargetBones];
AnimationData[] temp = new AnimationData[nSourceBones];

AnimationData[] targetData = new AnimationData[nTargetBones * nFrames];

// Get a map where map[iTargetBone] = iSourceBone or -1 if no such bone
int[] map = parseBoneMap(source, target, boneMapFilePath);

for(int iFrame = 0; iFrame < nFrames; iFrame++)
{
int sourceBase = iFrame * nSourceBones;
int targetBase = iFrame * nTargetBones;


// Copy the root translation and rotation directly over
AnimationData rootData = targetData[targetBase] = sourceData[sourceBase];

// Get the source pose for this frame
Array.Copy(sourceData, sourceBase, temp, 0, nSourceBones);
source.getAbsoluteTransforms(temp, sourceTransforms);

// Rotate target bones to face that direction
Matrix m;
AnimationData.toMatrix(ref rootData, out m);

Matrix.Multiply(ref m, ref target.relatives[0], out targetTransforms[0]);
for(int iTargetBone = 1; iTargetBone < nTargetBones; iTargetBone++)
{
int targetIndex = targetBase + iTargetBone;
int iTargetParent = target.hierarchy[iTargetBone];
int iSourceBone = map[iTargetBone];
if(iSourceBone <= 0)
{
targetData[targetIndex].rotation = Quaternion.Identity;
Matrix.Multiply(ref target.relatives[iTargetBone], ref targetTransforms[iTargetParent], out targetTransforms[iTargetBone]);

}
else
{
Matrix currentTransform, inverseCurrent, sourceTransform, final, m2;
Quaternion rot;

// Get the "current" transformation (transform that would be applied if rot is Quaternion.Identity)
Matrix.Multiply(ref target.relatives[iTargetBone], ref targetTransforms[iTargetParent], out currentTransform);
Math2.orthoNormalize(ref currentTransform);
Matrix.Invert(ref currentTransform, out inverseCurrent);

Math2.orthoNormalize(ref inverseCurrent);

// Get the final rotation
Math2.orthoNormalize(ref sourceTransforms[iSourceBone], out sourceTransform);
Matrix.Multiply(ref sourceTransform, ref inverseCurrent, out final);
Math2.orthoNormalize(ref final);
Quaternion.RotationMatrix(ref final, out rot);

// Calculate this bone's absolute position to use as next bone's parent
targetData[targetIndex].rotation = rot;

Matrix.RotationQuaternion(ref rot, out m);
Matrix.Multiply(ref m, ref target.relatives[iTargetBone], out m2);
Matrix.Multiply(ref m2, ref targetTransforms[iTargetParent], out targetTransforms[iTargetBone]);
}
}
}

return new SkeletalAnimation(target, targetData, animation.fps, nFrames);
}

c# - Pathfinding for units of variable size



I'm using a grid map for a top-down RTS, and using a* for pathfinding. Specifically, I've found one implementation which is heavily optimised, and I've been using it for a while, but now I've realised I only checked it with infantry and not with vehicles, which take more map space, and so I can't rely on the algorithm - what would be "hugging a cliff" for infantry would be passing through it for a vehicle.


So, I'm trying to decide what to do. I see three options. a. The obvious thing is write my own A* implementation, but this is both very time consuming and I presume I won't reach near the optimised speed of the algorithm I found. (rewriting the algorithm is out of the question - I just don't have the time to try to read it and understand it).


b. corrections - read the path generated by the algorithm, and either correct it at every step or when receiving the path recalculate it for width.


c. Hold variable sized maps, that are different representations of the free space on the map, on account of size.


Option C sounds to me the simpolest, but is likely to be too memory heavy, even if there're only three-four size categories. Between options a & b, I'm not sure what is likely to take more calculation time - a non-optimised A*, or running over & correcting a path.



Answer



A* is not a hard algo to understand and it is one you should get intimately familiar with if you plan on using it in games.


What you really need from your description is an annotated pathfinder. (clearance based) There is a great description of one here.


Clearance Based Path Finding


This article describes a hierarchical annotated a* path finder however once you can write your own A* from scratch adding features you need for each project is very simple.



Heavy use of a profiler will help you optimize your path finding in short order. It really is a simple piece of code once you get the hang of it.


Edit: I am sorry I forgot to add. If you already have a fast a* the modification to add the clearance based checks is pretty simple. Obviously your base object that anything that is going to use the path finder is derived from needs a "clearance" variable of some kind.


Inside the actually path finder just find the spot where it is checking against if things are walkable or not and that is where you add in the clearance checks. Also when you first generate your map you need to add a var to the node or however your graphing your map to pre-calculate the clearance values.(that will make it faster) Really that is basically all there is to it.


mathematics - How to compute the moves amount in a match-3 game?


I have a match-3 mobile game, similar to these popular games in the store. Mechanics are different, but the gameplay stays the same:



  • NxN board

  • X moves

  • Y objectives to complete to win

  • tons of different levels. When you complete a level, you unlock a new one


When you run out of moves, you have to buy moves or try again, so you have to think on each move.


And the problem is in the moves, I'm trying to calculate the amount of moves required for each level. I want it to be be slightly lower than the average, so it takes 3-4 attempts for an average player to complete.



I discovered that "being stuck" 2 or 3 times on a level makes it a lot more fun, than completing levels each time with a single attempt.



I have couple hundred players and with them - some statistics. With each level attempt (lost or won) I save it on my server to use it for calculations:


ID | Level Number | Used Moves | Lost/Won

Then, each week, I compute a sum of attempts on each level, and I do this for all players. Then, I compute a mean average on each level:


avg_lvl_attempts = sum_level_attempts / player_count

So if 3 people took level 10, all of them with 4 attempts, it would be:


avg = (4 + 4 + 4) / 3 = 4


Which means that it takes the players 4 attempts, on average, to complete level 10. Then, based on that, I increase the amount of moves on level 10 by a small amount, so it's a little bit easier for them (because I want to achieve 3 on average). And I do that for each level.


The problem with that solution is that it can produce strange results, for instance if someone had 130 attempts (it happens sometimes).



Is there any algorithm, or mathematical trick to do these kind of things more accurately, like excluding edge cases etc?




copyright - How can I handle intellectual property violations in user-generated content?


I recently made a simulation game like Gamedev Tycoon where you are in charge of a game company and planning to release it on app stores soon.


I have few questions about trademark and copyright laws, as in game there are different companies (competitor) who release games, make sequels to previous games, release consoles etc. I know that under parody law I can change a company name from MICROSOFT to MICROCRAFT or MINORCRAFT etc. But what if I provide users an editor where they can change company names (if they want to) from MICROCRAFT to MICROSOFT?


Do changes made by players with my editor violate any copyright or trademark law? How can I handle that?



Answer





But what if I provide users an editor where they can change company names (if they want to) from MICROCRAFT to MICROSOFT?



Generally, when you provide tools that allow your users to produce content for your game, you'll want to include in your game's license agreement terms that dictate how and what may be produced. The single- or multi-player nature of the game isn't really an issue, the issue is if the content can be reasonably expected to be distributed by users. It almost certainly always can.


For example, Skyrim is a single-player game that includes official modding tools in the form of its Creation Kit. The EULA for the Creation Kit requires that:



You shall not create any New Materials that infringe upon the rights of others, or that are libelous, defamatory, harassing, or threatening, and You shall comply with all applicable laws in connection with the New Materials.



This kind of clause helps to indemnify you, the author of the software, against intellectual property violations perpetuated by (and appearing to be part of) your software.


Include such a clause in your EULA.



Wednesday, December 23, 2015

unity - FB.Init() is not accepting in my c# Script



I am trying to connect fb with my game. its first time i am connecting fb with game. i downloaded fb SDk 7.3.0 and i am using unity 5.2.1f1. i imported the sdk in my game asset. then i created a new c# script "FBholder". in Awake() i tried to use FB.Init(). but its not accepting. all other scripts used inside the game are calling correctly, only the scripts came with fb sdk is not working.


 using UnityEngine;
using System.Collections;

public class Fbholder : MonoBehaviour {

// Use this for initialization
void Awake() {
FB.Init (SetInit, OnHideUnity);// This line is not accepting
}

}

i Used this Video for my referance



Answer



You have not included the correct namespace for FB.


Write using Facebook.Unity; at top of your class.


Here is the sample script for using Facebook with common features, such as posting score, with latest SDK.


using Facebook.Unity;

List perms = new List (){"public_profile", "email", "user_friends"};


void Awake ()
{
if (!FB.IsInitialized) {
// Initialize the Facebook SDK
FB.Init (InitCallback, OnHideUnity);
} else {
// Already initialized, signal an app activation App Event
FB.ActivateApp ();
}

}

private void InitCallback ()
{
if (FB.IsInitialized) {
// Signal an app activation App Event
FB.ActivateApp ();
// Continue with Facebook SDK
// ...
} else {

Debug.Log ("Failed to Initialize the Facebook SDK");
}
}

private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {

// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}

private void AuthCallback (ILoginResult result)
{
if (FB.IsLoggedIn) {
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;

// Print current access token's User ID
Debug.Log (aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log (perm);
}
} else {
Debug.Log ("User cancelled login");
}
}


// On Facebook login button
public void OnFacebook ()
{
FB.LogInWithReadPermissions (perms, AuthCallback);
}

education - Is a computer science degree worth it?



I'm in my last year of high school, and I've been looking at colleges. I'm taking a C++ class at a local community college and I don't feel that it's worth it. I could have learned everything in that class in a week.


This had me thinking, would a CS degree even be worth it? How much can it teach me if I can learn everything on my own? Even if I do need to learn more advanced subjects, many colleges put their material online AND I can buy a book. Will companies hire me if I don't have a CS degree? If I have a portfolio will I stand a chance? What kind of things are needed in the portfolio?


I want to live doing what I love - programming. So I will do it. I'm just not sure that a CS degree will do anything to me. In addition, if there is a benefit to getting a CS degree, what places are the best?



Answer



As a burned-out, bitter, and cynical programmer with >10 years in the industry, this would be my advice:


Don't plan on games as a long-term career.


Plan to do it for a few years, get it out of your system. But plan for a more sensible career longer-term, and don't leave it too late to make that change


You might manage 5-10 years in the industry, then you'll realise that there's not much long term future in being made redundant every 1-2 years, and crunching like crazy to buy the higher-ups supercars whilst barely seeing any pay rises, let alone bonuses.



Also, the industry changes at quite a pace. When I was at high school age, it was all about the Amiga, 16-bit consoles, and 2D games. By the time I came out of university, it was all about 3D and Playstations. These days, the 'big games' industry is in a worse state than ever, can't see it lasting many more years as things are. But we have a resurgence in bedroom coding/indie development, and new opportunities in mobile devices and web-based platforms.


Change can be exciting, but generally change means layoffs. Layoffs force salaries down. Changing job means relocating... Most people can't keep doing it for all that long...


open source - Are there any implemented game controls like a screen (thumb) joystick? - iOS


I'm looking for some open source game controls. Especially I'm looking for a thumb screen joystick to move a character on the screen, something like a touch circle.


Are there any open source implementation of what I'm looking for?



Answer



There's a button and virtual joystick implementation for cocos2d called "SneakyInput". Here's a tutorial that might help you use it.


physics - How does pixeljunk shooter simulate its liquids?



I am really impressed by the liquids in pixeljunk shooter. I would love to know how they do it.



Answer



There is an excellent SIGGRAPH presentation on PixelJunk Shooter 2's lighting and physics simulation, including fluid mechanics, available on youtube.


word usage - missing preposition 'for' before time


When can we omit 'for' before time noun ?


In below examples, the preposition 'for' is omitted before a time frame is specified.



In the afternoon we drive 20 minutes to the Eden Project.


We work 5 hours a day.



Walk 30 minutes every day.


We are going to the town two hours from now.



But in case of a similar verb 'run', I've never seen such omission of 'for'.



Answer



With longer periods of time you should probably use "for." If the period of time is unspecified, "for is definitely required. For example, "I searched for hours!" "For" always specifies duration, so you could never say "we are going to the town for two hours from now." Idiomatically, you can use "for" to express a specific time, like "we're going to the town for 2:30." That usage of "for" means "we expect to arrive at such a time." In general, "if you can append "a day," "a week," "a month," or "a year," to the end of a sentence, you can omit the "for." "I fly six hours a week between Vancouver and LA." "They're open six hours a day." While you can use "for" in those circumstances, it usually doesn't carry any specific meaning.


Tuesday, December 22, 2015

grammar - What is the difference of "go to", "go over to" and "go up to" to "X's place"?



In the following sentence:



I am going to go to my daughter's house.


I am going to go over to my daughter's house.


I am going to go up to my daughter's house.



I have difficulty understanding these differences (my dictionary doesn't even have the definition of go over that is relevant to this usage). For me all seem the same, but what is the difference between them?




past tense - I was wondering vs. I am wondering vs. I wonder


If I would like to make requests, should I use “I was wondering…” instead of “I am wondering…” and “I wonder…”? If yes, what’s the most appropriate situation to use “I am wondering…” and “I wonder…”?




tiles - Is the Manhattan distance monotonic when used as heuristic function?


I have a square-based map. Only horizontal and vertical movement is allowed (no diagonals). Movement cost is always 1.


I'm implementing an A* algorithm on that map, using the Manhattan distance as a distance heuristic. Is this heuristic consistent? Can I can avoid checking g(node) against nodes that are in the CLOSED set?


Edit: By consistent I mean monotonic.




Answer



To actually answer your question: the manhatten distance is consistent when you're constrained to moving vertically/horizonally along an unweighted grid (this can be easily shown by the definition on wikipedia). So yes, in your case you can avoid rechecking nodes in the closed set.


However, once you allow diagonal or any-angle movement, manhatten distance becomes nonadmissible because it overestimates diagonal costs, which necessarily means it's not consistent.


libgdx - Movement and rotation of bodies in top down game


We are developing a 2D top down game with libgdx using the included box2d as physics engine.


We don't want our bodies to accelerate but to instantly move with the wanted velocity. The bodies are moved like this, which works perfectly for our purpose:


Vector2 currentVelocity = body.getLinearVelocity();
Vector2 targetVelocity = velocity.velocityApplyVector.cpy();
targetVelocity.sub(currentVelocity);

targetVelocity.scl(body.getMass());


body.applyLinearImpulse(targetVelocity, body.getWorldCenter(), true);

The problem now is, that we also want the bodies to instantly rotate to the direction they are facing. The direction of the player is determined by the mouse position, so it is possible that the body is moving in another direction than it is facing. I tried to accomplish it like this:


float bodyAngle = body.getAngle() * MathUtils.radDeg;
float totalRotation = (inputRotation - bodyAngle) % 360;
if(Math.abs(totalRotation) > 1) {
if ( totalRotation < -180) totalRotation += 360;
if ( totalRotation > 180) totalRotation -= 360;
float impulse = body.getInertia() * totalRotation;
body.applyTorque(impulse, true);

}

This causes the body to rotate in the wanted direction but it needs multiple frames until it totally reaches the wanted angle.


The body mass is set to 70 and the angular damping to 8 (I tried some values for the damping and 8 was the best value for my cause, but that's, of course, not a final solution...).


I guess I have to somehow increase the needed impulse depending on the body mass and the angular damping (we want to be able to change it) but I can't figure out how to get the values right. I don't want to use setTransform since it totally destroys the physically correct behaviour of the bodies. How can I calculate the needed values? Is there any better way to solve my problem?



Answer



Simple Solution


If you want the body to instantly rotate just call Body::setTransform and pass the current position and the desired angle, don't bother applying torques or anything.


The function call could be something like this:


body.setTransform(body.getPosition(),myDesiredAngle);


Physics Solution


If you want the player body to interact with bodies while rotating to the cursor position (i.e. you can knock them out of the way) then I would recommend another method:


FollowCursor setup


The numbers in the figure above are described here:



  1. The player body. An isoceles triangle shows the direction the body is pointing

  2. A kinematic body. This is not necessary for your game, it just plays the roll of continuously moving the player to the right while allowing it to face another direction. It is connected to the player body via a revolute joint

  3. A cursor body. This body should not collide with anything. This body will follow the cursor as closely as possible (more on that later)

  4. A wheel joint connecting the player body to the cursor body. We really want it to act as a slider (prismatic joint), but we also don't need to constrain the angle of the cursor body. This joint will force the player body to face the cursor body at all times. As such we want the frequency, damping ratio, motor speed, and max motor speed all set to zero.



The result:


followcursor gif


Now you will notice that in the rube editor it's just the mouse (mouse joint) that I used to move the cursor body around, and I didn't achieve the instantaneous rotation you are looking for. But do not dispair, because you can get around this in one of two ways:



  1. Set the transform of the cursor body at every step like described in the simple solution above. I'm not sure that this won't break physics all the time. If the player body is locked in a corner it might just move through other bodies to satisfy the joint constraint.

  2. Create a second cursor body. Connect the second cursor body to the first using a motor joint (box2d 2.3.0). I used a max force of 10N and a correction factor of 0.90. In the game, the transform of the second cursor body is then set to the position of the cursor every time step.


In the gif below, the second cursor body is the larger square body:


follow cursor motor joint



As a side note, the motor joint was surprisingly stable. I tried to get it to work with a distance joint and kept getting jitters and/or cases where the high damping caused a slow contraction of the joint.


My intuition tells me there will still be kinks for you to work out. The problems you encounter will depend on your gameplay.


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