Thursday, October 31, 2019

How can I use Rectangle.Intersect() to resolve collisions in XNA?


I have a 2D game written in XNA, and I've been trying to fine-tune my collision resolution. All of my game objects are squares, which means detecting a collision is easy - use the position and the size of each entity (which is already known) to craft a corresponding Rectangle, then compare the two with Rectangle.Intersect().


This works fine for the most part, but has been running into weird corner cases where the collision resolution doubles an entity's jump height, or gets caught between tiles when moving horizontally across a flat surface.


I have recently expanded my code to include a velocity for each game entity, and I thought it would be possible to avoid some of these problems by preventing the need for these resolutions in the first place.


The idea would be to use an entity's position + velocity to predict a collision, then reduce the velocity to prevent a collision from occurring in the first place.


I can still use Rectangle.Intersect() to determine if the entity is in a collision, but I'm horribly confused on how to go from the Rectangle returned by Rectangle.Intersect() to an appropriate velocity counter-vector to avoid the collision.


Is there a straightforward way to go from the intersection Rectangle to an appropriate counter-velocity?



Answer



I've actually implemented this just the other day. I started from the XNA Platformer Sample but noticed it had a few problems on corner cases. This was especially noticeable when using it for Zelda-like movement, because the character would get stuck between tiles when hugging the walls in a certain direction. I tried several changes to the algorithm, but there would always be one direction where the problem would appear.


I looked around a bit, and although I was skeptic, ended up trying a simple solution that I read in one forum - and it worked! So, instead of moving the player all at once and then resolving each collision along the smallest axis of intersection depth, the trick was to update and resolve on the X and Y axes separately. The process is still very similar to before, except for that difference. In other words:




  1. Apply horizontal velocity to your position.

  2. Round position.X to prevent jittering on some edge cases.

  3. Iterate through each obstacle that the player is intersecting, calculating the horizontal intersection depth and subtracting it from the player's position so that he no longer intersects that obstacle.

  4. Repeat 1-3 but for the vertical axis.


And so far it seems to be working, even when trying different player sizes and movement speeds, and "hugging" every wall in every direction. I've also noticed that as long as I cap the maximum instantaneous speed to the smallest value between the player's size and the tile's size, then he won't ever funnel through the walls. And that's still moving pretty fast!


I intended to clean it up a little, maybe make it completely generic, and release on my blog one of these days. But meanwhile I'll just drop every relevant bit of the code in a pastie, albeit unorganized, so you can read through it:


http://pastie.org/3152377


And here's a little video of that code in action, where I'm forcibly trying to push against every wall. I used normal a player size slightly smaller than the tile, and a normal movement speed, but I've also tested with many different values.



Edit


By the way, I'm using a custom method to get the intersection depth (basically the one from the Platformer sample modified to work on 1 dimension at a time) instead of Rectangle.Intersect. That's mostly because while Rectangle.Intersect gives you the depth, it does not give you the direction of the intersection, so you'd need to do some extra checks to find that out.


meaning - What is the difference between "look", "see", and "watch"?


When should I use "look", "see", and "watch"?



I'm watching "Star Trek".
Have you seen "Star Trek"?



Are the examples above correct?



Answer



Here are some simple rules that will help deciding which word to use:





  • See is used as inactive word; you just see without any effort:



    • you have visual impression: "I can see my home over there", "I see trees of green"

    • you understand: "I see what you mean"




  • Look is used as active word, you make an effort to see:




    • you try to see: "look at this!" (maybe you have to turn your head or stand up)

    • you pay an attention: "to look for a baby"

    • you search for something: "you can look up the word in the dictionary"




  • Watch is also an active word; you also make an effort, but it is for a longer period of time:



    • "I'm watching "Star Trek", "I like to go to a zoo and watch tigers playing"

    • pay attention: Watch the kittens as they may run away.





Here's an example demonstrating the difference:



I'm looking, but I don't see it.



Back to examples:
I'm watching "Star Trek" — it is a continuous action;
Have you seen "Star Trek"? — it is a question if you ever seen it at all, or do you know about it;

It can be also formulated: Have you watched "Star Trek" all night?, and it will mean that you have spent all night watching a movie.


See also: (1), (2).


collision detection - How to optimize the distance function?


While developing a reasonably simple RTS-like game, I noticed my distance calculations were causing an impact in performance.


At all times, there are distance checks to know if a unit is in range to its target, if the projectile has reached its target, if the player has run over a pickup, general collision, etc. The list goes on, and checking for distance between two points is used a lot.


My question is exactly about that. I want to know what alternatives game developers have for checking distances, other than the usual sqrt(x*x + y*y) approach, which is fairly time consuming if we are performing it thousands of times per frame.



I'd like to point out I am aware of the manhattan distances and squared distance comparisons (by skipping the sqrt bottleneck). Anything else?



Answer



TL;DR; Your problem is not with performing the distance function. Your problem is performing the distance function so many times. In other words you need an algorithmic optimization rather than a mathematical one.


[EDIT] I am deleting the first section of my answer, because people are hating it. The question title was asking for alternative distance functions before the edit.


You are using a distance function where you are calculating square root everytime. Yet, you can simply replace that without using the square root at all and calculate the distance squared instead. This will save you a lot of precious cycles.



Distance^2 = x*x + y*y;



this is actually a common trick. But you need to adjust your calculations accordingly. It can also be used as initial check before calculating the actual distance. So for example instead of calculating the actual distance between two points/spheres for an intersection test we can calculate the Distance Squared instead and compare with radius squared instead of radius.


Edit, well after @Byte56 pointed out that I didn't read the question, and that you were aware of the squared distance optimization.



Well in your case, unfortunately we are in computer graphics almost exclusively dealing with Euclidean Space, and distance is exactly defined as Sqrt of Vector dot itself in euclidean space.


Distance squared is the best approximation you are going to get (in terms of performance), I can't see anything beating 2 multiplications, one addition, and an assignment.



So you say I can't optimize the distance function what should I do ?



Your problem is not with performing the distance function. Your problem is performing the distance function so many times. In other words you need an algorithmic optimization rather than a mathematical one.


The point is, instead of checking player intersection with each object in the scene, each frame. You can easily use spatial coherency to your advantage, and only check the objects that are near the player (that are most likely to hit/intersect.


This can be easily done by actually storing those spatial info in a spatial partitioning data structure. For a simple game I would suggest a Grid because it's basically easy to implement and fits dynamic scene nicely.


Every cell/box contains a list of object that the bounding box of the grid enclose. And it's easy to track the player position in those cells. And for the distance calculations, you only check the player distance with those objects inside the same or neighbor cells instead of everything in the scene.


A more complicated approach is to use BSP or Octrees.



graphics - Which image format is more memory-efficient: PNG, JPEG, or GIF?


Which image format is more efficient to save memory? PNG, JPEG, or GIF?



Answer



"Memory" and "efficiency" are commonly misused terms, so I'll give you an answer for four different elements that may affect the performance of your game.



I will be oversimplifying way too many things to keep it short and concise, but there are tons of inaccuracies in this text below, so take it with a pinch of salt. However, the main concepts should be understandable.


Storage


This is the size your images consume on your software distribution. The more space your resources consume, the longer the download (as in from your website) will be. If you're distributing on physical media, such as CDs or DVDs, you're probably going to have to do some serious optimizations in this front.


In general, JPEG compresses the best for photographs and images with no sharp borders. However, your images will have degraded quality because JPEG uses lossy compression (you can fine tune the compression level/degradation when exporting images as JPEG. Refer to your imaging software's documentation for more information on this).


However, as good as JPEG may be, it doesn't support transparency. This is crucial if you want to have images that show through others, or if you want images with irregular shapes. GIF is a good choice, but it has been largely superseded by PNG (there's only a few things GIF supports that PNG doesn't, but they're largely irrelevant in game programming).


PNG supports transparency (and semitransparency), compresses data without degradation in quality (i.e. it uses lossless compression), and compresses fairly well, but not as much as JPG.


The problem arises when you need good compression, as well as transparency. If you don't mind slightly degraded images, you can use PNG quantization programs such as pngquant, which you can test online at TinyPNG. Keep in mind that the image degradation performed by quantization on its own is different than that of JPEG (which includes quantization as well as other aggressive techniques), so be sure to try both, with a wide variety of settings.


If you want to aggressively minimize your distribution size, you could manually process every image like this:


if the image has transparency then
try pngquant on the image

if the results are not satisfactory then
revert to the non-quantized image
end
store as PNG
else
try storing it as JPG with different quality settings
if no single setting yields an image of an acceptable quality then
try pngquant on the image
if the results are not satisfactory then
revert to the non-quantized image

end
store as PNG
else
store as JPG
end
end

Tip: it is okay to store some images in one format, and others in another format.


There are other specialized formats such as DXT, ETC and PVRTC. They support compression, and can also be loaded compressed into memory, but they are only supported by specific GPUs, and most of these GPUs only support one of them, so unless you know the exact hardware specifications of your target hardware (a notable case is the iPhone/iPad, which supports PVRTC textures), you should avoid these formats.


Program Memory



I included it here, because this is what's commonly known by "memory". However, if your game uses graphics acceleration (and if you're making a game after 1998, you most likely are), then the only thing that will consume memory are your texture descriptors (just a few bytes per image), which is only effected by the amount of images, and not their size or format (this has a few caveats, but are mostly irrelevant).


If your platform does not have dedicated video memory, is not hardware accelerated, or other uncommon cases, then the next section regarding VRAM will happen completely or partially in RAM, but the main principles will be the same.


Video Memory


This is where your images will be stored once your program is running. In general, the format in which you stored them will make no difference here, as all images are decompressed before loading them into video memory.


Now, the VRAM consumed by your images will roughly be width * height * bitdepth for each image loaded in VRAM. There are a couple of things to notice here:




  1. The width and height in which your images are stored in VRAM will not necessarily match the ones of your original image. Some GPUs can only handle textures with sizes in powers of 2, so your 320x240 image may actually be stored in a 512x256 space in VRAM, with the unused memory effectively wasted. Some times you're not even allowed to load textures with sizes that are not powers of 2 (like in GLES 1.1).


    So if you want to minimize VRAM usage, you may want to considering atlasing your images, and sizing them with powers of 2, which will also have the advantage of fewer render state changes when rendering. More on this later.





  2. The bitdepth is very important. Usually textures are loaded into VRAM in 32-bit ARGB or 32-bit XRGB, but if your hardware can support 16-bit depths, and you don't mind having a lower bitdepth, you can half the amount of VRAM consumed by each image, which may be something interesting to consider.




  3. But no matter what you do, the most important factor when considering the amount of VRAM your game uses, is the amount of images you have in VRAM at a given time. This is the number you most likely want to keep as low as possible if you want a good performing game. Loading and unloading textures into VRAM is expensive, so you can't just load each image whenever you're going to use it. You must find a balance between preloading the images you will most likely use, and unload them when you're sure you're not going to use them anymore. Doing this right is not trivial, and you have to think of your own strategy for your particular game.




Execution speed


Even though not "memory", it is very related with performance in games. Drawing images is expensive, and you want to make sure your rendering runs as fast as possible. Of course, in here, format doesn't matter, but other things do:





  1. Image size (actually, it would be "sampling size"): the biggest the region of an image you're going to draw, the more time it will take to draw it. Rendering a huge image in a small section of the screen is not very effective, so there is a technique called mipmapping, which consists of trading VRAM for rendering speed, by storing your images several times at several resolutions and using the smallest one that can give you the required quality at any given time. Mipmapping can be performed when the images are loaded, which will impact loading speed and VRAM usage, or at preprocessing (by manually storing different versions of the same image, or using a format that natively supports mipmapping such as DDS), which will impact storage and VRAM usage, but will have little impact on loading speed.




  2. Render state changes. You will most likely want to draw several different images on the screen at the same time. However, the GPU can only use a single source image at any given time (this is not true, but please bear with me here). The currently used image for rendering is one of many render states, and it is expensive. So if you're going to use the same image several times (remember when I mentioned texture atlases?), you will notice a huge performance gain if you reuse an image as much as you can before you change the render state and start using a different image (there are other render states apart from this, and fine tuning the order in which you draw your stuff to minimize render state changes is a very common activity when enhancing the performance of a game)




However, image usage optimization is a very complex topic, and what I wrote here is a very broad and oversimplified overview of some of the factors you will have to consider when writing a game, so I think it's definitely best if you keep it simple, and only optimize whenever you really need to do so. Most of the times, prematurely optimizing is unnecessary (and sometimes even detrimental), so take it easy.


Wednesday, October 30, 2019

textures - UV interpolation is wrong with a wide FOV


How should I take FOV into account when interpolating UV coordinates? This picture shows the result today. Everything works fine with a narrow fov, but when I make it really wide, things deviate. The black line is expected to be straight. I'm writing a software renderer myself, so I can't just invoke some OpenGL function. Any advice is appreciated.


Broken UV interpolation


https://bitbucket.org/jevring/threedee



Answer



UV interpolation needs to take into account the depth of the vertices.


You need to perform perspective-correct interpolation, which involves dividing by the w coordinate of the interpolated homogeneous vector.


Texture mapping approaches


The "folded plane" effect of affine interpolation becomes more pronounced at wide FOV or when the camera is close to an object, but it's not caused by the wide FOV itself. It's just that narrow views approximate an orthographic camera, which doesn't need perspective correction since it doesn't experience perspective.


Wikipedia gives an equivalent formulation without homogeneous coordinates. if the endpoints you're interpolating have coordinates u_0 and u_1, and an interpolation factor a, then your interpolated u_a lies at



Affine texture mapping formula for affine texture mapping,


which becomes


Perspective-correct mapping formula for perspective-correct mapping,


where z_0 and z_1 are the distances of the endpoints from the viewer, along the axis perpendicular to the image plane.


Is this type of sentence an Inversion?


I have heard this type of sentence with the same structure every time: 'Beautiful as she is', 'Intelligent as he is...'


Is it grammatically correct and if it is what's this grammatical phenomenon called? How do you end such a sentence? I believe it's Inversion but I'm not sure.


For example with a sentence beginning like this 'Young as she is...' how would I end it?




What should be learned for someone starting in Android Games?



I know this might be a little subjective. But I've read the other questions. A lot of answers kept on popping up like to use box2d, libgdx, andEngine, etc. So the real question is, what would be the best to start off with as a beginner.


I have some experience with java code, just by reading about in the Oracle Docs. I've gone through Flash and Eclipse. When i mean gone through, i don't mean i have actually created my own game from Flash or Eclipse, but i just learn things here and there.



Currently I'm reading Beginning Android for Beginners but I don't have the knowledge to implement my own Ideas into the game tutorials because of lack of experience.


I'm looking for a way to learn how to program to create games for Android. While at the same time get experience from programming. I do not want to learn those drag and drop game making applications such as GameMaker.


I'm looking just to make 2D games.



Answer



The best way to start making games would be to start making games. Don't get caught up with too many details such as which books should I read or what engine should I use, just pick something and get started. Every moment you spend debating how to start is a moment you've lost. You're first few projects probably won't be your best work anyways. The important thing is that you start gaining experience with making games. So don't worry about perfection, just get started.


Do you have any ideas for a game you would like to create? Try to define the game as precisely as possible before you start coding. Focus on identifying your "core" concepts, what makes the game fun. For example: the core concept of Portal is the portal mechanics, going in one and out the other. From that core, they designed puzzles, action, and story that build off of the ability to create portals. A core concept is usually a game mechanic, although it can sometimes be something else like a theme in the story. Just focus on your core while designing your game and don't add too much extra while you're just getting started. Keep your goals and designs as small as possible because creating a game is infinitely more work than it first appears to be. Stay focused, stay small, and get started.


If you don't have an idea for a game already, a good place to start would be cloning a popular or classic game. Many developers start by making Breakout or Tetris. You can even put your own ideas into it if you'd like.


Good luck and have fun! Also, welcome to GameDev!


java - What is the velocity of a translating projectile in 2D?


What I'm trying to do.


So I want to have a projectile that starts at point (x1, y1) and head in the direction of my mouse say point (x2, y2).


To clarify I'm pretty sure it's a vector but I don't know much about them.


Language / Librarys


I'm making the game in Java and LibGDX so Java.MathUtils would come in to play i'm pretty sure. If anyone that can answer don't know these languages, psuedocode will be just fine.


How I've tried it


I'm pretty sure the formula is something alongs the lines of velX := cos(radians) * speed velY := sin(raidans) * speed


And radians starts out as Pi/2 though the tutorial was pretty rough.



Then it would be x += velx * deltatime and same with y.


Can anyone help me out with the translation formula



Answer



You need to learn a little bit more about vectors but I'm going to explain it anyways.


First of all, let's say that your 'game unit' is in pixels and that points (coordinates) and vectors have two components x and y.


Let's assume that you have two given points A = (x1, y1) and B = (x2, y2).


To get the vector between A and B, you have to do the following formula: V = B - A. Since B and A have two components, we can translate this into V = (xB-xA, yB-yA)


enter image description here


However, this vector is pretty much useless because the length of it is the length of the line between A and B. If you have something like this


V = mouse.pos - projectile.pos

projectile.pos += V

it will instantly move the projectile to the mouse because - well - you're asking to move the projectile to the mouse..


The idea here is to get a direction from your projectile (point A) to your mouse or whatever object (point B).


enter image description here


So.. how do we get this direction ? Well, it's easy, the formula is u = V/length(V)


This procedure is normalizing where you just get the direction of a vector and completely ignore its length (sometimes called 'magnitude').


Adding this vector u to your position will move your object 1 unit away from its current position.


The point of it ? Moving your projectile towards a point with a fixed 'speed', like this:


projectile.pos += u * 10;


this code will move your projectile 10 units (let's say pixels) towards your mouse.




EDIT: Note that with this method you don't need to use trigonometry to compute the normalized vector; that means that neither you have precision loss (floats, pi, ...) nor confusing conversions with radians. That's a win :)




EDIT2: For consistence and clarity, I used the word vector and position but these "concepts" are the same: a point has an X and Y component as well as a vector.


In the code you would use the same data structure. Unfortunately I don't know java but I can provide you a c++ example:


struct MyData //That would be public class in java I beleive
{
float x;

float y;
}

Here MyData is a structure that allows two components: x and y. This structure is used for points as well as vectors; eg:


MyData point_a;
MyData point_b;
MyData vector_between;

//Instantiate and/or initialize values ...


vector_between = point_b - point_a;

In C++ there is a concept (operator overloading) that makes you able to perform custom operations between data structures (such as point_b - point_a in the above example). This is really useful because the program won't know how to subtract two "MyData" together unless you write your own method.


I don't think Java enables you to do this "hack", so instead of


vector_between = point_b - point_a;

you could write


vector_between.x = point_b.x - point_a.x;
vector_between.y = point_b.y - point_a.y;


this is what I meant where I directly used "pos" without the associated component.


Moreover, when I used length(V) I meant sqrt(V.x*V.x + V.y*V.y), that is the length/distance between two points (Pythagorean theorem, right ?)


NB: Usually the MyData data structure is, by "convention" called a Vector2 in 2D, Vector3 in 3D etc...


algorithm - Path finding in games


I am writing my term paper about Path finding algorithms in games, and i've got a couple of questions, hopefully you people could help me out with those ;)



So, i've done a little bit of searching around here and stumbled on this question. Now, the things are explained nicely there, but i wonder if anyone got examples of games using those? (obviously A* won't be hard to find, it seems to be quite popular now). I figured that BFS or DFS would probably be found in some older games but I'm not that familiar with those, perhaps someone knows a couple that might be using those algorithms so i could investigate deeper?


Also, i'm having trouble figuring out the strong/weak sides of those algorithms compared to each other, as in when should i use BFS instead of Dijkstra's Method for example, from both efficiency and mechanics point of view? (If amount of available memory isn't the issue). Or is A* an answer to all the prayers and there is no reason not to use it?


Any help would be appreciated!



Answer




when should i use BFS instead of Dijkstra's Method



BFS applies to unweighted graphs only. Dijksta's is just an extension of BFS to weighted graphs - Dijksta's on an unweighted graph will examine exactly the same nodes as BFS.


So, they can essentially be viewed as the same algorithm.




Or is A* an answer to all the prayers and there is no reason not to use it?



A* is just an extension of Dijkstra's algorithm, which speeds it up by using a distance-heuristic.


Dijkstra's and A* are for much more general problems than just pathfinding on a grid: they can be used to pathfind on any directed, weighted graph. A distance-heuristic for these won't always be possible; that's when Dijkstra's should be used.


However, if you have a heuristic available, there is no reason not to use A* - it will always be as-fast or faster than Dijkstra's. For pathfinding in games, which often just involve units moving through 2D or 3D space, you usually have a distance-heuristic (the actual distance between the points), so A* should be chosen over Dijkstra's.




The reason A* is often chosen over more complicated algorithms for games is that it's simple to understand and implement, yet fast enough for our needs. The biggest mistakes when using A* for games is not using the wrong algorithm, but implementing it incorrectly. For example, it is not well-known that ties must be broken towards the endpoint, and amateurs often incorrectly run the pathfinder every frame.


There are other algorithms that are sometimes used, though. A rather recent algorithm that is gaining popularity is Theta*. It is like A*, but gives the unit freedom to move in all directions (which is common in games). The old approach to do this was using A* + linear interpolation, but Theta* gives better results, with very little cost to speed or complexity.


Another interesting one which I recently wrote a post in is HPA*, which is a useful way of decreasing the search-space to make searches go faster (at the cost of returning non-optimal results)





You can read about more about different pathfinding algorithms here. However, some of them are extremely complicated, and very few of these will actually give much benefit for most games anyhow - as a game programmer, it suffices to just learn and understand A*.


word usage - Can I use the prefix "Non-" instead of other negative prefixes?


Would there be any difference? For instance,






  1. I don't want to talk about non-important issues. (unimportant)




  2. He is a very non-active/non-sexual person. (inactive) (asexual)




  3. This is a non-logical assumption. (illogical)








physics - How do I make a vehicle move to a point and stop without overshooting or oscillating?


Ok so consider we have a vehicle like the one I described in my answer to this question, with a 2D position, velocity, angular velocity, and drag/friction. It can accelerate and break by a variable amount, but not stop dead instantly or reach top speed instantly. How can I make it move to a particular point and stop - in the fastest time possible - without overshooting or oscillating?


I was thinking something like:



  • turn towards target position.

  • accelerate

  • look 1 tick ahead, asking "If I applied the breaks next tick, would I overshoot the target?"

  • If it would overshoot, apply the breaks now by some amount.



I'm sure this is a solved problem and there is a probably a better method than the one I described.




meaning - Does "has been nothing short of amazing" mean it is a short time interval?


From this book "Deep Learning and Convolutional Neural Networks for Medical Image Computing"



While the use of deep learning by the medical image processing community trailed that of the computer vision community by a couple of years, the uptake of deep learning in medical research has been nothing short of amazing.




I googled this and found a lot of "Today has been nothing short of amazing"


Does "has been nothing short of amazing" mean it is a short time interval?




Tuesday, October 29, 2019

word choice - "Shall" versus "will" for the first person


When I studied English, I was taught that shall is used to express the future tense for the first person (singular, or plural), and will is used for the same purpose in the other cases.


When I look for shall on the NOAD, I read the following sentence, in a note about the usage of shall:



In practice, however, shall and will are today used more or less interchangeably in statements (although not in questions).




Does that mean shall and will are used with almost the same meaning?


Does I shall return have the same meaning of I will return?



Answer



The NOAD is right. As ‘The Cambridge Guide to English Usage’ comments:



*Will is now the standard choice for expressing future plans and expectations, everywhere in the world. Shall is stylistically marked with volitional meaning in legal and regulatory statements, and expresses politeness in first person questions.



passive voice - Being+past participle as a gerund


I've read that 'being+past participle' is used in participle.But I'm confused to have found the following sentences written in one of my grammar book(This book isn't available in internet) as gerunds.These sentences are:




  1. He is afraid of being hated.

  2. I remember being taken to Delhi as a small boy. 3.Being frightened wouldn't solve any problems.



My questions: 1. What's the meanings of above sentences?



2.In which condition this "being+p.p"construction is used as gerunds to make sentences?




Monday, October 28, 2019

word usage - inform about vs inform of



What is the difference between "inform of" and "inform about" ?


Can you give some example sentences which clearly shows the difference.


Thanks.



Answer



I think inform of merely talks about the 'information of something' and that's it!


Say...



I'll have to inform her of Joe's kidnapping



So, here, we are informing her that Joe is kidnapped. And that is all!



On the other hand,



I'll have to inform her about Joe's kidnapping



Means, not only will she be informed that Joe is kidnapped but also the details.


android - Best way to implement achievement system?


I'm currently trying to implement achievement system for my game. However, I can't find a better way to realize some complex ones like: The player has collected x coins, complete level with time least than x seconds, Kill over x enemies etc. Can you share your experiences please?


Secondly, Why don't we just implement achievement system as local only instead of using server like Scoreloop or OpenFeint? Or put it in another way, What are the advantages of using server for managing player's achievement?



Answer




An achievement system can be pretty complex. Many of the achievements are special cases that need to be watched for. That means special code, just for that achievement. Some will be easy to code for, like finishing a level under a certain amount of time or total number of coins collected. As simple as having a timer or a global counter. The more complex achievements, obviously, require more complex code. Killing x type of enemies over x number of seconds would could require a rolling counter or detailed logging with regular analysis.


Basically, if you want achievements, you need to code them in. Just like any other feature. As the developer you have access to all the information about the game, you just need to log what happens and see if it matches your achievement requirements.


I plan on implementing my achievement system into the event system. Since I'm already sending significant events to be logged, I might as well let the achievement system listen in. This is nice because then all the code for achievements is in one place. So for example, you could fire an event each time a level ends. The event would include all the information about the performance of the player on that level including their score, time to complete, number of coins collected and so on. Those events are read by the event system and logged. You can then keep running totals of coins collected and compare finish times to previous bests.


As for the server for managing achievements. I believe one of the big draws with achievements is sharing them with others, or comparing your achievements to your friends. Having the achievements hosted publicly implements the social features that are appealing to many types of gamers.


EDIT


Absolutely you can avoid hard-coded rules! The system I describe is mostly for collecting information and getting it all into one place. That would be best hard-coded and you will have to hard-code collection code for any additional rules. You try to collect as much significant data as you can, so you'll have more to work with later.


How you analyze the data is up to you. Incoming events can be filtered by rules defined in JSON or Lua. As for implementing Lua, I've not done that, so I don't know if it's easy to do. I imagine it is. Lua is a very powerful scripting language with plenty of resources to help if you get stuck. Seems like a good choice to me.


actionscript 3 - As3 Flash How to check if a bitmapdata is completely set to transparent using an eraser?


I'm trying to make a window-cleaning game with flash as3 on the timeline. (Sounds boring I know, but I realy have some fun idea's with it)


So I have: A dirtywindow movieclip on the bottom layer and a clean window movieclip on layer 2(mc1) on the layer above.


To hide the top layer(the dirty window) I assign a mask to it.


// this creates a mask that hides the movieclip on top
var mask_mc:MovieClip = new MovieClip();
addChild(mask_mc)

//assign the mask to the movieclip it should 'cover'
mc1.mask = mask_mc;


With a brush(cursor) the player wipes of the dirt ( actualy setting the fill from the mask to transparent so the clean window appears)


//add event listeners for the 'brush'
brush_mc.addEventListener(MouseEvent.MOUSE_DOWN,brushDown);
brush_mc.addEventListener(MouseEvent.MOUSE_UP,brushUp);

//function to drag the brush over the mask
function brushDown(dragging:MouseEvent):void{
dragging.currentTarget.startDrag();
MovieClip(dragging.currentTarget).addEventListener(Event.ENTER_FRAME,erase) ;

mask_mc.graphics.moveTo(brush_mc.x,brush_mc.y);
}

//function to stop dragging the brush over the mask
function brushUp(dragging:MouseEvent):void{
dragging.currentTarget.stopDrag();
MovieClip(dragging.currentTarget).removeEventListener(Event.ENTER_FRAME,erase);
}

//fill the mask with transparant pixels so the movieclip turns visible

function erase(e:Event):void{
with(mask_mc.graphics){
beginFill(0x000000);
drawRect(brush_mc.x,brush_mc.y,brush_mc.width,brush_mc.height);
endFill();
}

}

I hope you can help me with the following problem: The game-aspect of this should be the points the player get's for cleaning/erasing all the dirt.



Can anyone tell me how I can check if all pixels are set to transparency? So how to check if all the dirt has been erased? And than for example trace ("window cleaned")




I tried the compare() function but didn't have much luck with it :(...



Answer



A naive approach would be to simply perform a brute-force check on all pixels. As soon as you hit a non-transparent pixel you can stop searching further. This won't work very well with large images and can result in quite extensive searches if the last non-transparent pixels are at the end of the search.


There are two better ways I can think of:




  1. Similar to a brute-force check, start in the top-left (0, 0) of the image and check every pixel to see if it's non-transparent. If you hit a non-transparent pixel, the image isn't clear yet. So store that position and in the next iteration, start from that pixel instead (because all previous pixels have been marked as transparent anyway, so there's no point in checking them again). Your image will be cleared as soon as your search-position reaches the last pixel in the image.





  2. Calculate the sum of total pixels (eg. image.width * image.height) and store that in a variable. With every drawing-operation you count the amount of pixels that were set to transparent and subtract this value from the total. As soon as your total hits zero, you cleared all pixels. To count the pixels that turned transparent in one drawing-operation, you sample the brush area (for example by using bitmap.getPixels()) and count all the non-transparent pixels before you do the drawing operation.




Sunday, October 27, 2019

movement - Moving a ship forward from rotation


I am making a simple space simulator, where the player can control a ship using 2 controls, one for pitch and one for bank. The ship is properly rotated but I cannot figure out how to make the ship move forward based on that angle. Here's what the code looks like right now:


func renderer(renderer: SCNSceneRenderer, updateAtTime time: NSTimeInterval) {

let t=CGFloat(time - lastTime)


ship!.transform = CATransform3DRotate(CATransform3DRotate(CATransform3DRotate(ship!.transform, ud*t, -1, 0, 0), 0.00, 0, 1, 0), lr*t, 0, 0, 1);

ship!.position = ?

}

I tried every combination of vector, euler angles, matrices, quaternions that I could think of/read about with no success. I am probably missing something stupid but cannot find what it is.


The code is in Swift using Scenekit, but language doesn't matter that much to me and I can translate any algorithm. It's also worth noting it does not work like Unity and Quarternions/Vectors don't have properties like .forward() etc.


Thank you for your help!





verb agreement - "A variety" singular or plural





  1. A variety of pleasant items in the shop attract [plural] everybody.




  2. A variety of animals are kept at the zoo.





  3. A wide variety of dishes is essential for a successful restaurant.




  4. A variety/range of products exists.





As far as I know "A variety" takes singular verbs.


Now my doubt is that in #1 and #2 it uses plural verb but in case of #3 and #4 it uses singular verb. Why so?


So does "A variety " takes singular or plural or both?



Somewhere on internet I read that we should treat "A variety" the same way we treat "A number". Is this true?


Some examples are also given:




  • A number of people are causing trouble.




  • The number of troublemakers is only about ten.





  • A variety of books are on the table.




  • The variety of books on the table is unbelievable.




I don't know if these are correct or not.



Answer



For any word or phrase that implies a set (e.g. variety, assortment, multitude, group, collection, lot, etc.), the best way to decide whether to treat it as singular or plural is to ask yourself "am I referring to the set's members, or to the set itself?" If you're referring to the set's members, use plural. If you're referring to the set itself, use singular (because, even though a set contains multiple things, it is a single thing).


Some examples might help to clarify this distinction. Imagine a florist conversing with one of her customers...



Example 1:



Customer: I'd like to have a bouquet sent to my wife for our anniversary. Would roses be a good choice?


Florist: Certainly, but consider mixing some daisies and lilacs in with the roses. A variety of flowers makes a lovely anniversary bouquet.



Note the use of the singular verb makes in the last sentence. Since the set is being treated as singular, we assume that the florist is making a statement about the set rather than its members. In other words, it's the variety, not the flowers, that she's identifying as that which makes a lovely bouquet.


Example 2:



Customer: I'd like to have a bouquet sent to my wife for our anniversary. Would roses be a good choice?


Florist: Certainly, but roses aren't your only option; you could send daisies or lilacs instead. A variety of flowers make a lovely anniversary bouquet.




The last sentence is exactly the same as the previous example's, except that the singular verb makes has been replaced with the plural make. The grammar is still correct, but the meaning has changed. This time, the florist is saying that any of the set's members can be used to create a lovely bouquet. She's not suggesting that the bouquet should contain the whole set (as in the previous example).


So both forms are correct, and the one you should use depends on the message you're trying to convey.


It's worth noting that many native English speakers-- myself included-- often mess this up, so you'll probably have to use context to figure out what we mean most of the time. Plural verbs seem to be preferred when the necessity of distinguishing between the set and its members is absent or unclear. In fact, you could probably get away with always using plural verbs. This is somewhat ironic since singular verbs have the advantage of not conflicting with the indefinite articles a and an (e.g. a variety, an assortment), which are exclusively singular. But for some reason, we prefer to break the rules in this case.


One reason may be the verb's close proximity to the noun that identifies the set's members (e.g. the flowers in "a variety of flowers"). Since that word is plural, it "feels right" to follow it with a plural verb, even if the actual subject of the sentence (the set) is singular.


Another reason may be that phrases like a variety of, a lot of, an assortment of, etc. are often used as substitutes for adjectives like various, many, some-- words that typically describe plural subjects and are therefor accompanied by plural verbs (e.g. "various flowers make lovely bouquets"). When people make this substitution, they may not feel comfortable changing the verb to its singular form because in their minds, they're still referring to multiple things as opposed to one.


So there is some gray area, but most of the time you'll do well to follow the rule described at the top of this post.


Note on definitions: The word variety has several meanings, of which the most relevant to the current topic is "diverse set". When it's preceded by the word the, as in "the variety of books on the table is unbelievable", it usually means "diversity" or "type". Those meanings have their own usage rules which are beyond the scope of this answer.


Saturday, October 26, 2019

What does Word mean by "passive voice"?



I have requested an agent to cancel my tickets in email as shown below



It helps if I get a confirmation once the request to cancellation of the ticket has been updated.



But, my Outlook (this is Microsoft email application, which uses the dictionaries and rules from Word) shows an error prompt for grammar correction.


enter image description here


It says "Passive voice (consider revising)"


So, what is wrong here? What is "passive voice"?




progressive aspect - I'm giving up vs. I give up


Are both of the following sentences grammatically correct and, if so, is there any siginificant difference between simple and progressive aspect here?



I give up (on sth. / sb.)


I'm giving up (on sth. / sb.)






javascript - Creating a frozen bubble clone



This photo illustrates the environment: http://i.imgur.com/V4wbp.png


I'll shoot the cannon, it'll bounce off the wall and it's SUPPOSED to stick to the bubble. It does at pretty much every other angle. The problem is always reproduced here, when hit off the wall into those bubbles. It also exists in other cases, but I'm not sure what triggers it.


What actually happens: The ball will sometimes set to the wrong cell, and my "dropping" code will detect it as a loner and drop it off the stage.



**There are many implementations of "Frozen Bubble" on the web, but I can't for the life of me find a good explanation as to how the algorithm for the "Bubble Sticking" works. **


I see this: http://www.wikiflashed.com/wiki/BubbleBobble https://frozenbubblexna.svn.codeplex.com/svn/FrozenBubble/


But I can't figure out the algorithims... could anyone explain possibly the general idea behind getting the balls to stick?


Code in question:


    //Counstruct our bounding rectangle for use
var nX = currentBall.x + ballvX * gameTime;
var nY = currentBall.y - ballvY * gameTime;
var movingRect = new BoundingRectangle(nX, nY, 32, 32);
var able = false;


//Iterate over the cells and draw our bubbles
for (var x = 0; x < 8; x++) {
for (var y = 0; y < 12; y++) {
//Get the bubble at this layout
var bubble = bubbleLayout[x][y];
var rowHeight = 27;

//If this slot isn't empty, draw
if (bubble != null) {
var bx = 0, by = 0;


if (y % 2 == 0) {

bx = x * 32 + 270;
by = y * 32 + 45;

} else {
bx = x * 32 + 270 + 16;
by = y * 32 + 45;
}


//Check
var targetBox = new BoundingRectangle(bx, by, 32, 32);
if (targetBox.intersects(movingRect)) {
able = true;

}
}

}


}



cellY = Math.round((currentBall.y - 45) / 32);

if (cellY % 2 == 0)
cellX = Math.round((currentBall.x - 270) / 32);
else

cellX = Math.round((currentBall.x - 270 - 16) / 32);

Any ideas are very much welcome.


Things I've tried:


Flooring and Ceiling values Changing the wall bounce to a lower value Slowing down the ball


None of these seem to affect it. Is there something in my math I'm not getting?



Answer



Model the playing field as a hexagon grid. Each bubble is actually a hexagon shape for its connections:


enter image description here


Each flat side is where a bubble can connect. When a bubble touches another bubble, snap the bubble in motion to the nearest hexagon grid location.



Finding the nearest is essentially a picking operation, so the math for finding where the bubble will stick is the same. You can find some great answers for that here.


Friday, October 25, 2019

word usage - cousin vs cousin sister



Someone told me that we can't use brother or sister with cousin. Please check the examples and let me know which one is correct?




  1. My cousin brother asked me to come with him

  2. My cousin asked me to come with him



Which one is correct?




opengl - Protecting game assets through archiving


I'm writing a game in C++ (with OpenGL) and am getting quite far into development. Currently I'm loading the data directly from different directories.


(E.G. I load textures from a /Data/Textures/...png)


This is fine, but not preferable. Ideally I would like to protect these assets without too much of a performance hit. I looked at other games that I own, both Indie and AAA and found that the majority of them archive the data. However, I am unable to access these archives with programs like Winrar Archiver which implies that they have some level of protection.


I'm not particularly knowledgeable in the field of encryption and data storage, so I may be overlooking something obvious but I would like to know how exactly I could achieve something similar.


(I am aware that competent individuals are able to use the GPU to gain access to the data but that's not preventable)



Answer



As others have said, there is no real protection for your assets. That doesn't mean you have to push them out there totally unprotected, though.


Having your own internal format for your assets is pretty useful or even necessary in the long run anyway. If you have your own file format that is not easy to open in content creation tools then it serves just as much for security as any kind of archive system.


You can do the same as well for image formats. I mean do you really want to store 80 types of files in a shipping game anyway? You can have an internal variable or encoding of some kind if you really want additional protection - or if you want to have the ability to have some files protected and others not.



I would make it so that you do not do this by default though, it is a serious drag for people working on your engine. Just allow for a deploy batch job that protects all the files for you before shipping.


A package is nice too so people can't even see file names, but it is pretty pathetic as a security measure, it just means you have put every file together and hidden the directory structure, really. So you make it harder on modders but don't really provide any security.


As for the issue of protection itself, I don't think it matters a lick if you are just putting a game out there. Why make it hard for people to mod whatever dumb stuff they want in there? Sometimes the mods can really help a game look better for that matter.


Yet you are probably going to need it eventually if you expect to have third party customers using things. Especially if you want people making various art packs for your engine. There's nothing that can really stop a determined thief but they won't make a pack for your engine at all unless you have some sort of provision to protect their work.


unity - How to make sure an object NEVER passes through an edge collider (2D)?



In my top down perspective game, I have a ball that bounces off of walls. The ball should behave in a way where it will always bounce off in a 90 degree angle. The ball can only move up, down, left and right and the walls are slanted so that they should always (theoretically) bounce a ball up, down, left or right.


On the ball object, I have a small circle collider 2D and a Rigidbody 2D attached, the walls have a single edge collider 2D attached. Approximately one time out of twelve times, the ball will simply pass through the edge collider, so it's not consistent.


How can I make sure that the ball always registers the collision?


Here's my setup:


enter image description here


The script I use to move the ball:


void Update () {
switch (direction)
{
case 'u':

transform.Translate(0f, ballSpeed * Time.deltaTime, 0f);
break;
case 'd':
transform.Translate(0f, ballSpeed * -1 * Time.deltaTime, 0f);
break;
case 'l':
transform.Translate(ballSpeed * -1 * Time.deltaTime, 0f, 0f);
break;
case 'r':
transform.Translate(ballSpeed * Time.deltaTime, 0f, 0f);

break;
}
}

Additional info:
- every wall is it's own object with it's own edge collider.
- the ball always hits the center of the wall because I center the ball object using the center of the wall it touches. Note: I had issues with the ball passing through walls even before I implemented the centering.




terrain - Demystifying "chunked level of detail"


Just recently trying to make sense of implementing a chunked level of detail system in Unity. I'm going to be generating four mesh planes, each with a height map but I guess that isn't too important at the moment. I have a lot of questions after reading up about this technique, I hope this isn't too much to ask all in one go, but I would be extremely grateful for someone to help me make sense of this technique.



1 : I can't understand at which point down the Chunked LOD pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this.


2 : I understand that a Quadtree data structure is used to store the Chunked LOD data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level?


3a : How is the camera distance usually calculated. When reading up about quadtree's, Axis-aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?)


3b : Do the chunks calculate the camera distance themselves?


4 : Does each chunk have the same "resolution". for example at top level the mesh will be 32x32, will each subdivided node also be 32x32. Example below:




example of chunked LOD



Answer



1 : I can't understand at which point down the Chunked LOD pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this.


It does not matter. For example, you can integrate the chunking into your mesh generation algorithm. You can even do this dynamically, so that lower levels are added dynamically (e.g. as player moves closer) using a plasma-like refinement algorithm. You can also generate a high-resolution mesh from artist input or elevation measurement data and aggregate it up into all the LOD chunks at asset finalization time. Or you can mix-and-match. It really depends on your application.


2 : I understand that a Quadtree data structure is used to store the Chunked LOD data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level?


Not necessarily. The tree just stores information about the geometry and how to render it. This could mean having an vertex/face list at every tree node. More realistically in this day and age, you would store the handles of the meshes/instances in GPU memory.


3a : How is the camera distance usually calculated. When reading up about quadtree's, Axis-aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?)


A very cheap and easy option is to use the distance to the centre point of the chunk and then correct it. You know that this distance is always an underestimation: if the centre point is at distance Z, this means that half the chunk is closer than that. What we do not know however is the orientation. If we are viewing a chunk of width w edge-on, the closest bit of the chunk will be at distance Z-w. However, if we are viewing the chunk corner-first, the closest bit will be at distance Z-sqrt(2)*w. If you can live with this uncertainty (you almost always can), you are done. Note that you could also correct for the viewing angle using basic trigonometry.


I prefer to calculate the absolute minimum distance from the camera to the chunk to minimize artifacts. In practice, this means doing a point-square distance test. It's a bit more work then calculating distances to the centre points, but it's not like you'll do a zillion of these every frame.



If you can leverage your physics engine to do this then by all means do so, but you really want to think about it more in terms of "distance query" than "collision".


3b : Do the chunks calculate the camera distance themselves?


It really depends on the design of your engine. I would recommend keeping the leaves relatively light-weight though. Depending on your platform, just the call overhead of having a few thousand terrain-chunks perform their own update every frame can seriously impact performance.


4 : Does each chunk have the same "resolution". for example at top level the mesh will be 32x32, will each subdivided node also be 32x32.


They do not have to, but it's convenient if all chunks take up the same amount of space. Then you can do your (GPU) memory management in units of "chunks". It's also easier to remove / hide the seams between two chunks of different sizes if one resolution is a multiple of the other because they share more vertices. (e.g.: 32x32 and 64x64 is easier to manage than 32x32 and 57x57) (thanks Guiber!). If you have a good reason to vary the chunk geometry size, by all means go for it.


What is billboarding, and can/should it be used in 3D games to create special effects for weapon blasting effects?


What is billboarding, and can or should it be used to create special effects for 3D games on weapon blasting effects?



Answer




What is billboarding ?



Billboard is a textured flat object, usually a polygon, which faces the camera. Its direction usually changes constantly as the object and camera move, so it always faces the camera direction, this operation is called Billboarding. Billboards usually use texturing + alpha to represent many phenomena that do not have smooth solid surfaces (e.g. Clouds, Grass, Smoke, Fire).



Can or should it be used to create special effects for weapon blasting effects?




You need to make a distinction between billboards and particle systems. A particle system is a set of small objects that are animated and controlled using an algorithm. Particles can be represented by Billboards, but other forms are also common such as points and lines. You can make gun blasting effects using billboards, but in the end, you will need a way to control those billboards which will end you up making a particle system (though might be a very simple one)


Thursday, October 24, 2019

sentence construction - What's the grammatical structure of "all three of them periods"?


Oxford Guide to English Grammar; John Eastwood; Oxford University Press 1994-09


Page 54




2 Information in a text


a In a text, old information usually comes first in the sentence and new information comes later.


ELEGANT BUILDING
Britain's towns were given a new and an elegant appearance between 1700 and 1830. This period covers the building styles known as Queen Anne, Georgian and Regency, all three of them periods in which houses were very well designed.


Previously, towns had grown naturally and usually had a disorderly, higgledy-piggledy appearance. In the new age, architects planned whole parts of towns, and built beautiful houses in terraces, or in squares with gardens in the middle.


The houses of these periods are well-proportioned and dignified, with carefully spaced windows and handsome front doors. They can be seen in many towns, especially in London, Edinburgh, Bath, Cheltenham and Brighton.


Brighton became famous after 1784 when the Prince of Wales, later King George IV, went there regularly, and later built the Royal Pavilion.


(from R. Bowood Our Land in the Making)


The subject of each sentence is something expected in the context. Usually it relates to something mentioned earlier.




What's the grammatical structure of "all three of them periods" (sentence in bold)?




related: subject vs subject-complement; inversion




sentence construction - How to say thank you for the ....?


Consider below chronological events.


I sent an E-mail to a professor and asked him a question. He answered my question. Now, I want to send him a message and say thank you ... .




I need a short and formal sentence implying a sense of being modest, but not very modest!. e.g., "I am not a special person and his contribution to my question illustrates his great benevolence"




I have written:






  1. Thanks for the time you considered for my question.






  2. Many thanks for the time you dedicated to my question.







  3. I appreciate you for including my question in your considerations.







Do the above sentences sound awkward ? If so, any suggestion would be appreciated.




meaning - Are "aside from" and "besides" exchangeable in this case?


This is one of the examples from cambridge dict



Do you play any other sports besides basketball?



Oxford dict consider "besides" and "aside from" are synonyms.


Assume the guy being asked loves basketball and baseball, are "aside from" and "besides" exchangeable in the example sentence?




Wednesday, October 23, 2019

Can adjectives make a noun definite?


If we use an adjective for a countable object so it makes it specific, then can we use "the" before it?


For example to me "the green color" or "green", means "the color that is green among the known colors". As another example "the green continent" to mean the continent which is green (Europe)?


I asked a similar question when to use "the" before abbreviation,for example DOM is the abbreviation for Document Object Model, as I checked some documents, they may use the DOM tree but DOM trees. it seems DOM make the tree specific.


I borrowed these examples from the answer of the question, as he suggested to ask more details in another question.



The Asian elephant has smaller ears than the African elephant.




If I am correct, then I would like to know a general rule about when an adjective can cause a definite article and when it can't.



Answer



"The" applies any time when you are referring to a single unique item in a set. Adding more adjectives makes your reference more and more specific, and at some point there may be only one thing that meets that description, and then it appropriate to use "the".


For example, let's say you are in a hat shop, trying to get a specific red hat. If you ask for "the red hat", they will be confused because the shop has many red hats and they don't know which one you mean. Instead you would say "a red hat", indicating that any red hat will do.


Alternately, you could keep adding adjectives until you reach something unique. You could instead ask for "the large, red, sparkly hat with a peacock feather". There is only one of those, so there is no confusion.


It can be a little more confusing than this. Take your example:



The Asian elephant has smaller ears than the African elephant.




This works because "the Asian elephant" refers to the genus Elephas, commonly known as the Asian elephant, and African elephant refers to the genus Loxodonta. So they are talking about these two groups in specific, rather than any elephant from Asia, or any elephant from Africa. Otherwise, it would only be appropriate if they had a group of elephants that they had previously referred to, and only on of those was Asian and only one was African.


You also expressed some confusion on "the color green" vs "the green color". "The color green" refers to a specific color that is named "green". Although many colors are green, every manufacturer of pigments has one color they consider to be the true green and so they name it green. If you open a box of Crayola crayons, for instance, many of them will be a green color, but only one of them will be labelled "Green". That is the one that someone would be referring to if they asked you to pass "the color green". On the other hand, "a green color" is a color that is green. All of the crayons in that box that have a mix of blue and yellow pigments would fall into this category. To be able to use the definite article, you need to narrow it down further. If you were admiring a car that was painted some shade of green, you could say "I really like the green color on that car", because you are referring specifically to the color that is on the car, and no other green.


In the case of "the DOM tree", you are referring either to a single DOM tree, or to the abstract concept of DOM trees in general. While many things qualify as DOM trees, there is only one class of trees referred to as "DOM tree" and so the definite article is appropriate. If you had several DOM trees, you would not use the definite article, but if you had several different trees, and one of them was a DOM tree, you could refer to that one specifically by saying "the DOM tree".


Tl;dr:


You can use the word "the" any time when there is a single definite thing you are talking about, and you can use adjectives to narrow down your subject until there is only one single definite thing that meets your description.


mathematics - Matrix for 2D perspective


I'm trying to determine whether what I'm attempting to achieve is even possible mathematically. I'm obviously not a seasoned game developer so I'm having trouble even coming up with the terminology to pose this question.


My 2D game (and I must stress that it is 2D) has a perspective such that the "camera" looks down at the game world from 45 degrees. Here's a rough sketch describing the look I'm trying to achieve:


enter image description here



As objects move from foreground to background (such as the red box pictured), they not only get smaller but are moved towards the center of the screen. So whilst the on-screen representation is rectangular, the actual game world has this shape:


enter image description here


Now I suspect I can do all this without using a matrix. I've already got the scaling working and don't think it would be too difficult to offset on the x axis objects according to their distance from the camera.


However, what I'd really like to know is whether I can encompass this perspective inside a simple matrix. I've had a look around the web but have got lost in a sea of nomenclature that I don't understand and information that doesn't appear to be relevant to me (such as 3D camera positioning, etcetera).


Can anyone tell me whether I'm barking up the wrong tree? If it is possible, can someone point me towards some articles or blog posts that describe this in detail?



Answer



You are talking about doing manually something which is already done for you automatically by 3D APIs. One of the most basic functions of any 3D engine is to handle the transition from a bunch of objects in 3D space and a camera (naturally you must always have a camera) to a 2D picture (technically a projection) on the screen.


In your case, doubtless an object's representation moves more pixels per second going left or right than away from the camera, due to your angle (unless you deliberately have a fundamentally illogical physics model, like many such pseudo-3D games, and have those speeds be equal - not criticizing). This would be handled by what is known as the view matrix, which looks at where objects are in the world and says where they should be on the screen.


If objects far away did not get smaller, and the road away from you looked straight if it was straight (ie did not appear to narrow due to perspective) you would have the familiar isometric game. To make far away things smaller, and a few other similar things, you apply what is known as a projection matrix which pretty much takes what the camera sees, and "distorts" to show how it would look if the camera had an arbitrary lens. An isometric game has no projection matrix and thus everything is... Well, isometric.


There is usually a third kind of matrix, a world matrix, in 3D engines - because parts of 3D models are placed relative to the models origin, you need the world matrix for placing models in different points of your world. It's also like position and rotation (and scale, and skew if you have 4D matrices) of your object all in one handy mathematical entity.



So what you usually do is, you multiply (matrix multiply) these three matrices, and multiply the "model" (which is a bunch of points and polygons defined with respect to a model origin) in order to place a model's image on the screen. These matrices are not invariant, of course. For instance, the world matrix is generated depending on where your object moves.


I think isometric games are at the "2D threshold" - they are roughly the same amount of work Math-wise in 2D and 3D:



  • You can make a "2D" isometric game with an identity matrix for a projection matrix, and put all sprites on billboards (in the computer graphics meaning) but you'll still have to muck about with a quite superfluous "camera" to create the 3D transformation matrices.

  • You can make a 2D isometric game with sprite graphics, where you say directly where on the screen you want each sprite to be drawn (in the familiar x, y with regard to top left of the window fashion). But if you have, say an isometric RPG, and characters can jump, you'll still have to keep track of height and calculate the y coordinate accordingly, and if you don't do some trigonometry with sizes and speeds the game world will be very "strange" form a physics point of view.


However, once you do more 3D-stuff than a sprite-based isometric game would entail, as you are, I think it would be much less trouble to do everything in 3D, unless your goal is to make a 3D engine from scratch. As for your question, hopefully it is clear to you now that what you want to do can be done, it can be done easily, and it is routinely done by just about everyone out there who does 3D as a matter of course. To sum it up: Yes, it can be done, and it's fairly straightforward, but you shouldn't do it and would save yourself a lot of needless work if you just used a 3D engine.


For learning about linear algebra, you may find sources like the Khan Academy or the MIT lectures helpful. As someone who already knew linear algebra but had no idea how it applies to 3D graphics, I have found XNA and RB Whitaker's XNA tutorials very helpful and easy. They also explain using matrices for 3D like I did here, except better.


architecture - How do I ensure a piece of code runs only once?


I have some code that I only want to run once, even though the circumstances that trigger that code could happen multiple times.


For example, when the user clicks the mouse, I want to click the thing:


void Update() {
if(mousebuttonpressed) {
ClickTheThing(); // I only want this to happen on the first click,
// then never again.
}

}

However, with this code, every time I click the mouse, the thing gets clicked. How can I make it happen only once?



Answer



Use a boolean flag.


In the example shown, you'd modify the code to be something like the following:


//a boolean flag that lets us "remember" if this thing has happened already
bool thatThingHappened = false;

void Update() {

if(!thatThingHappened && mousebuttonpressed) {
//if that thing hasn't happened yet and the mouse is pressed
thatThingHappened = true;
ClickTheThing();
}
}

Further, if you wanted to be able to repeat the action, but limit frequency of the action (i.e. the minimum time between each action). You'd use a similar approach, but reset the flag after a certain amount of time. See my answer here for more ideas on that.


Tuesday, October 22, 2019

word usage - Is there any difference between being ill and sick?


I can say I'm ill or I'm sick. But what is the difference between the usage of these terms?


I've heard that one can use sick for longer-term and ill for shorter-term, but is that really correct? How are these terms different for native speakers?



Answer




While those might mean the same for the laymen, from a medical point of view, there is a difference between illness and sickness.



Medical sociology has long made the distinction between illness and sickness. Illness is the objective diagnosis that an external impartial observer is able to make based on the constellation of symptoms which the patient presents. Sickness is the social role that the patient adopts as the patient and other concerned stakeholders, in relationship with the patient, interpret the meaning of the illness.



From what I get of it, someone might see themselves as sick (with the social/role aspect of it) but not actually be ill (in a medical sense). Also, this paper might provide some useful reading.


deployment - PC game update systems



I've almost finished a PC game (I'm releasing it in a day or two). I'd like a way to easily release patches over the net in case I find a bug in the game right after release, or in case I want to add features later on.


I am using InstallJammer as my install system. Are there good update/patch programs (preferably free) which can check for and send updates to players over the Internet?


For instance, if a player opens my game, the game first starts the update program that checks for updates. If updates are available, it will let the user know where to get it. I can modify the source code to the game engine I own, but I'd prefer not to re-invent the wheel.



Answer




Thanks for all of the help guys, but after some looking around, I found a really good updater. It's called Puchisoft Dispatcher. They have a freeware version, and it is really good for non-commercial projects.


Monday, October 21, 2019

textures - Bad quality of the sprite in Unity


I need to import a few sprites (background platform and sky) into my game scene but it seems that their quality after importing into Unity is too bad (they are blurred). The original resolution of this two images is big enough (2048 X 400 for background) and they are looking very nice in standard Windows image viewer. Here are the settings for these two textures:


maxSize = 2048 Format = truecolor TextureType = Sprite(2d)/nGUI FilterMode - point


I am using Unity2D 4.5 Target resolution of my project is 1280*800.


Can anyone help me to solve these problem? As you can see the grass on foreground looks very bloory (1 picture) Texture settings (2 picture) Original image (3 picture)


enter image description here enter image description here enter image description here




nouns - Is the term 'Invalid' applicable for human beings?


As I was reading a novel 'What Katy Did', I came across an interesting mention of the word Invalid.



His wife was said to be an invalid, and people, when they spoke of him, shook their heads and wondered how the poor woman got on all alone in the house, while her husband was absent.



For me, it sounds off. Can invalid be a valid word for human beings?


I have heard about things like - the credit card is invalid, the transaction is invalid, your registration is invalid..., but how about your husband is invalid?




Answer



invalid there is a noun.



invalid (n) - Someone who is incapacitated by a chronic illness or injury.



Having this said, his wife seems to be very sick, in a crucial condition that might have made her incapacitated.


Now since there's discussion about the degree of being incapacitated (which makes you ultimately invalid), I'm adding a bit to improve this answer.


Here is another reference from OLD:



invalid (n) - a person who needs other people to take care of them, because of illness that they have had for a long time.




Now, if you look at both the definitions, you see that the term invalid ranges from someone being assisted by others to walk, eat or do routine activity to someone who is permanently bedridden (as in the last stage of cancers). Contrary to what Doc and FumbleFingers, it is not always necessary that invalid person is so so so sick that he/she is on the deathbed. And, I'm a doctor and have come across many such patients with chronic illness (in fact, have worked in hospitals that only take such cases).


The OLD further explains it in its example:



She had been a delicate child and her parents had treated her as an invalid



Furthermore, delicate here means:



delicate (n) - (of a person) not strong and easily becoming sick




That's where the WordWeb definition fits in. Invalid is someone who is incapacitated - not able to perform their tasks because of illness that has brought weakness. Here, the child does not necessary to have Ryley's tube or Folly's catheter as Doc mentions.


On the other hand, invalid does not always mean that the person is just incapable to do things and is not so critical. That's why I said, the term applies to incapacitation and this varies from degree to degree depending on the illness that person has.


Check this here:


enter image description here


If you see Saturnino Soncko (a person working in the silver mines of Cerro Rico), he's certainly invalid but I can still argue and deny calling him invalid as at least he is not that incapacitated! In that picture at least he is sitting without any assistance whereas invalid requires support even for this, don't they? They certainly do I see the woman every day. She is an invalid and cannot move anything other than her eyes.


Again, invalid is certainly a serious condition but it varies in degrees or severity depending upon the type of illness. I'm not sure to apply partially invalid or completely invalid for that though it might make better sense.


meaning in context - 'Great Lakes' is or are? Which one is correct?


In this article, I read the following lines:



The Great Lakes have claimed thousands of ships since European explorers began navigating the waters in the 1600s, but few have captured the public's imagination as has the Edmund Fitzgerald, which sank on Nov. 10, 1975, in Lake Superior.



To my mind, 'The Great Lakes' has claimed is correct.


Then I searched for 'the Great Lakes' and I got the following meaning from here:



The Great Lakes (also called the Laurentian Great Lakes,1 or the Great Lakes of North America) are a series of interconnected freshwater lakes located in northeastern North America, on the Canada–United States border, which connect to the Atlantic Ocean through the Saint Lawrence River.




My questions are: The Great Lakes looks a collective noun for a series of lakes, then why 'are' is used every time with it? Shouldn't they put 'is' instead of 'are'?



Answer



Both are possible. The difference isn't even in the meaning but of your preference. The expression



The Great Lakes are a series of...



points to the treatment of the lakes as several elements of one sequence ("series"). The expression



The Great Lakes is a series of...




points to the fact the those several elements constitute one single collection of elements.


Now, depending on the context (and it's provided by the remainder of the sentence), you can deduce whether singular or plural is necessary, or, if you decided to use one or the other, you need to keep it consistent. You can notice that the last clause in that entire sentence has the verb "connect". The use of that form prompts us to think that the plural is intended. Hence the verb "be" (before "a series") has the same form.



The Great Lakes (also called the Laurentian Great Lakes,1 or the Great Lakes of North America) are a series of interconnected freshwater lakes located in northeastern North America, on the Canada–United States border, which connect to the Atlantic Ocean through the Saint Lawrence River.



The relative pronoun "which" in the last [subordinate] clause relates to "the Great Lakes". If you use "is", then the word "which" will relate to "a series", which is singular, and hence you'd write



... , which connects to the Atlantic Ocean through the Saint Lawrence River.



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