Saturday, April 30, 2016

Whole map design vs. tiles array design


I am working on a 2D RPG, which will feature the usual dungeon/town maps (pre-generated).


I am using tiles, that I will then combine to make the maps. My original plan was to assemble the tiles using Photoshop, or some other graphic program, in order to have one bigger picture that I could then use as a map.


However, I have read on several places people talking about how they used arrays to build their map in the engine (so you give an array of x tiles to your engine, and it assemble them as a map). I can understand how it's done, but it seems a lot more complicated to implement, and I can't see obvious avantages.


What is the most common method, and what are advantages/disadvantages of each?



Answer




First off, let me say that 2D RPGs are near and dear to my heart and working with old DX7 VB6 MORPG engines (don't laugh, it was 8 years ago, now :-) ) is what first got me interested in game development. More recently, I started converting a game I worked on in one of those engines to use XNA.


That said, my recommendation is that you use a tile-based structure with layering for your map. With any graphics API you use, you're going to have a limit on the size of textures you can load. Not to mention the graphics card texture memory limits. So, considering this, if you want to maximize the size of your maps while not only minimizing the amount and size of textures you load into memory but also decreasing the size of your assets on the user's hard drive AND the load times, you're definitely going to want to go with tiles.


As far as implementation goes, I've gone into detail on how I handled it on a few questions here on GameDev.SE and on my blog (both linked below), and that's not exactly what you're asking so I'll just go into the basics here. I'll also make note of the features of tiles that make them beneficial over loading several large pre-rendered images. If anything is not clear, let me know.



  1. The first thing you need to do is create a tilesheet. This is just a big image that contains all your tiles aligned in a grid. This (and maybe an extra one depending on the number of tiles) will be the only thing you need to load. Just 1 image! You could load 1 per map or one with every tile in the game; whatever organization works for you.

  2. Next, you need to understand how you can take that "sheet" and translate each tile into a number. This is pretty straightforward with some simple math. Note that the division here is integer division, so the decimal places are dropped (or rounded down, if you prefer). How to convert cells to coordinates and back.


  3. OK, now that you've broken the tilesheet into a series of cells (numbers), you can take those numbers and plug them into whatever container you like. For the sake of simplicity, you can just use a 2D array.


    int[,] mapTiles = new int[100,100]; //Map is 100x100 tiles without much overhead



  4. Next, you want to draw them. One of the ways you can make this a LOT more efficient (depending on map size) is to calculate only the cells that the camera is currently viewing and loop through those. You can do this by fetching the map tile array coordinates of the camera's top-left (tl) and bottom-right (br) corners. Then loop from tl.X to br.X and, in a nested loop, from tl.Y to br.Y to draw them. Example code below:


    for (int x = tl.X; x <= br.X;x++) {
    for (int y = tl.Y; y <= br.Y;y++) {
    //Assuming tileset setup from image
    Vector2 tilesetCoordinate = new Vector2((mapTiles[x,y] % 8) * 32,(mapTiles[x,y] / 8) * 32);
    //Draw 32x32 tile using tilesetCoordinate as the source x,y
    }
    }


  5. Jackpot! That's the basics of the tile engine. You can see that it's easy to have even a 1000x1000 map with not much overhead. Also, if you have less than 255 tiles, you could use a byte array cutting down the memory by 3 bytes per cell. If a byte is too small, a ushort would probably suffice for your needs.


Note: I left out the concept of world coordinates (which is what your camera's position will be based on) since that, I think, is outside the scope of this answer. You can read up on that here on GameDev.SE.


My Tile-Engine Resources
Note: All of these are targeted at XNA, but it pretty much applies to anything – you just need to change the draw calls.



  • My answer to this question outlines how I handle the map cells and layering in my game. (See third link.)

  • My answer to this question explains how I store the data in a binary format.

  • This is the first (well, technically second, but first "technical") blog post about the development of the game I was working on. The whole series contains information about things like pixel shaders, lighting, tile behaviours, movement and all that fun stuff. I actually updated the post to include the content of the my answer to the first link I posted above, so you may want to read it instead (I may have added things). If you have any questions, you can drop a comment there or here and I'd be happy to help.



Other Tile-Engine Resources



  • The tile engine tutorial from this site gave me the basis I used for creating my maps.

  • I haven't actually watched these video tutorials yet because I haven't had the time, but they're probably helpful. :) They may be outdated though, if you're using XNA.

  • This site has some more tutorials that (I think) are based on the above videos. It may be worth checking out.


game design - How do you decide when your feature list is long enough?


I know a bit about this question but I find that there are quite a lot of diverse opinions on the subject?


I know from a players perspective that more options is almost always good. But on the other hand if it has multi-player more means higher complexity (meta game) both for the developers as well as players.


On development complexity and time constraints always go hand in hand. Another would be resource and platform constraints. Possible economic ramifications of holding back for later is sometimes a reason as well.


So from people experience here aside from the above when should features be cut or be for later release?



Answer



I'd say it's a two-step process for us:



  • Establish the game's goals.


  • Determine which features help us reach these goals.


The feature list is long enough when those two points match up. So:


1. Establish our goals -- Figure out all the things that we want the game to do for the player/reviewer/whomever, then state them measurably. For example, with our latest (see alpha test vid here), we want to do these:



  • Visuals: We want every review to mention that the visuals are unusual and sexy, especially for an indie title. This is important to us because gamers often use their eyes as a quick metric of quality (though, of course, it's just one of many!), and we want that to draw them in.

  • Exploration: We also want to reward folks for exploring the game. To put that measurably, we want something around a fifth of the player's game time is spent doing neat little things outside the core gameplay. This is important to us because (IMO), much of the delight of a game comes outside of expected, core areas (we think about how clicking on pieces in Starcraft amuses us).

  • Community: We want everyone to tell at least one friend about the game.


2. Determine features that help us reach those goals -- These almost fall naturally out of the above. So, the features that correspond to the above examples might look like this:




  • Visuals: As a small studio, if we want sexy visuals, we can't go up against EA or Sony on realism. So to approach the goal of remarkable visuals, one of the game's features is a surreal aesthetic. (From this, we're able to determine which tools we need, and so forth.)

  • Exploration: Tidbits corollary to the game's action fall out of this. In our most recent title, we dropped a quick reference to Ryo's questionable search for sailors in Shenmue. It was a silly throwaway, but people liked and talked about it!

  • Community: We're asking ourselves all the ways to make a game worth mentioning to a friend. Making it fun is #1, of course. But we could also reward the players with a special item or level if they tweet about it. Pokemon made it worth while to have friends pick up the game -- there are some critters you could only get by interfacing with other people.


When we go through this process, it helps us determine:



  • How much we need to implement for a minimum viable product (MVP).

  • What's most important, what can wait, and what we can drop altogether.

  • When we finally have all the features we need.



It's worth noting that we don't slavishly stick to these rules! More often than not, some awesomely interesting things come about as a result of mid-project prototyping and just general futzing around. Especially for small games such as ours.


Friday, April 29, 2016

architecture - noSQL - Is it a valid option for web based game?



Out of an opportunity and boredom, a friend and I decided to make a web based game. This is the first 'game' I will be making, since usually I program web apps in django.


I've opted to use the same framework for the game, but I am not totally sure about the data storage, since I cannot foresee future requirements and DB related issues. Lately, the noSQL movement is gaining force and I would like to explore that area.


Therefore I have the following questions:



  • Would a noSQL datastorage (document-based, such as MongoDB) would be suitable for a web-based game?

  • What are the issues that might arise using a conventional RDBMS, such as MySQL?


  • How to insurance data consistency amongst users with MongoDB, during gameplay or at timed events, such as cron jobs?


Game overview: Typical adventure game, with the player fighting monsters and gaining items and such.



  • Some data is static across all players: items, weapons, potion, maps, etc.

  • Some data tied to the player: inventory, metrics (stats), progress, etc.

  • A player might need to know the stats and state of another player

  • Scheduled tasks will be run at certain time interval




word choice - I need a book which/that(?) is cheap enough, but in which/that(?) there are cute photos


On the one hand the clauses are restrictive, on the other hand, there is a preposition in the second case, So, it seems the correct version is "I need a book that is cheap enough, but in which there are cute photos", but this sounds awful.


So, what is the correct choice?



Answer



You are correct, the sentence is




I need a book that is cheap enough, but in which there are cute photos.



and you are also correct that it is verbose, the suggested alternative



I need a cheap book with cute pictures.
I need an affordable book with pictures.
I need an inexpensive book with pictures.



might be better.



relative pronouns - Why is "that"/"which" omitted in this sentence?


In the sentence:



All the information you need is in these folders.




I would have expected to find:



All the information that/which you need is in these folders.



Why are those omitted?



Answer



Complementizers (words which introduce an embedded clause) can be elided in English.


So the answer to your question is: it is omitted simply because it can be omitted, and the writer and speaker chose to do that.


Sometimes speakers and writers take advantage of this and save a word, and sometimes they put in the complementizer that or which, even though it isn't necessary.


Complementizers can be omitted even in sentences like these: "Tell Bob Jones stopped by". Although at first glance it looks as if "Bob Jones" is one name, it doesn't make sense that way. Furthermore, in speech, it can be made clear where the break is.



gui - Is gameswf usable?



The project page indicates that it's pre-alpha code, and suggests the actionscript support is weak. Flash UIs are nice, so I was wondering if anyone has experience getting gameswf to the point where it will embed nicely in C++ (e.g. nice function bindings) and properly play a swf that uses typical modern actionscript.


Is there an alternative that doesn't carry the pricetag of a commercial product?



Answer



I'm not personally familiar with gameswf, so I can't comment on how capable it is, however if your target platform is Windows only (for now), I can point you towards Hikari.


It was originally built for Ogre3D but it should be fairly straightforward to port, and it's been used in commercial titles such as Zero Gear.


Best of all, it will play everything you can play with the most recent Flash player (just replace the ocx that comes with the SDK with a more recent version).


In the future, Hikari will simply become an Ogre3D wrapper for the cross-platform Akarui.


tense - Difference between (was thinking / thought / have thought / had thought)


Consider the following dialogue:



A: I think we should go to China for our holiday this year.


B: Sorry, what did you say? I was thinking about my work.



If I replaced "was thinking" with "thought", "have thought" or "had thought", would they be all acceptable in the conversation? Would each of them bring any difference in meaning?



Answer




Think of how B perceives it:



B: ... think think think think think think think—Sorry, what did you say?
A:                                          [blah blah]



B looks back and thinks of A's utterance as an event which is completely done, finished. Linguists call this view of an event the perfective aspect. Perfective aspect in the past is expressed using the past form of a verb, You said or You did say.


That event, A’s utterance, occurred at a time when B was in a state of thought which started before A's utterance and ended sometime after it. Linguists call this view of a state imperfective aspect. Imperfective aspect is expressed using a progressive construction; in this case, since the state lies in the past, B uses the past progressive construction I was thinking.


Perfect constructions like I have thought and I have been thinking express a state which arises from a previous event and is current at the point in time which you are talking about. Linguists call that time you are talking about reference time (RT). A present perfect construction has the present as its RT: it expresses a state which is current now, at the time of speaking. Since B is talking about a past event, his RT is the past; in that context a present perfect cannot be used.


A past perfect construction expresses a state with a past RT, a state which was current in the past, so you might think that I had thought or I had been thinking would be appropriate here. But the perfect construction does not express a state denoted by the lexical verb (think) in the construction, it expresses a state which arises from the state or event denoted by the lexical verb. B is not talking about the result of his thinking, he is talking about the thinking itself—so a past perfect construction doesn’t work either.


There is more about aspect here, and entirely too much about perfect constructions here. Be careful not to confuse perfective aspect with perfect constructions—they are entirely different things.





I make the appallingly sexist assumption that A is B’s wife, only because that’s how this conversation always plays out in my own household.


tense - The Present Perfect Progressive and the Simple Present Perfect


I'm trying to understand the difference between these two perfect verb-forms. Could you explain the difference between the following sentences:



I've been playing a lot of tennis recently.



and




I've played tennis three times this week.



I also would like to understand, what is verb-form preferred in my first sentence:



I'm trying to understand the difference between [...]



or



I have been trying to understand [...]






xna - Scene Graph for Deferred Rendering Engine


As a learning exercise I've written a deferred rendering engine. Now I'd like to add a scene graph to this engine but I'm a bit puzzled how to do this.


On a normal (forward rendering engine) I would just add all items (All implementing IDrawable and IUpdateAble) to my scene graph, than travel the scene-graph breadth first and call Draw() everywhere.


However in a deferred rendering engine I have to separate draw calls. First I have to draw the geometry, then the shadow casters and then the lights (all to different render targets), before I combine them all. So in this case I can't just travel over the scene graph and just call draw. The way I see it I either have to travel over the entire scene graph 3 times, checking what kind of object it is that has to be drawn, or I have to create 3 separate scene graphs that are somehow connected to each other. Both of these seem poor solutions, I'd like to handle scene objects more transparent.


One other solution I've thought of was traveling trough the scene graph as normal and adding items to 3 separate lists, separating geometry, shadow casters and lights, and then iterating these lists to draw the correct stuff, is this better, and is it wise to repopulate 3 lists every frame?




Answer



An approach I've used in a C++ project is that the scene-graph (which has the spatial index) fills up a 'visible' std::vector of hits based on the current viewing frustum. This visible list is managed by the scene-graph so is only recalculated when the camera moves - moving objects in the graph are moved in this list and using tombstones and unsorted change-lists that get sorted and merged back in as-needed.


The list of visible items is sorted by shader-ID first and within each type by distance from camera. The shader IDs are assigned such that terrain sorts first and then buildings and then units and then projectiles and then particles and so on - it being an RTS. Some models have more than one shader, but they only advertise their primary shader. When they are asked to draw, those which need bits drawn with another shader too add themselves to a next-pass single linked list.


So drawing goes through the visible array in one pass, and in that one pass a linked list of those items to revisit is created, and they get drawn a second pass and so on.


Drawing front-to-back and opaque-then-transparent helps keep everything sane.


This is perhaps not minimising the number of shader changes etc but it is fairly workable and straightforward to implement.


I have no idea about XNA and how applicable this is and how much of this low-level stuff you create I'm afraid. It would be most interesting to know what the veterans think of this approach for C++ RTSes however.


Thursday, April 28, 2016

c++ - Building a touch event driven UI from scratch: what algorithms or data types?



I have a touch display. As input I can receive the coordinates and how many touch points are in use, basically I just get an X,Y couple for every touch event/activated point at a customizable rate.


I need to start from this and build my own callback system to achieve something like Object.onUp().doSomething() meaning that I would like to abstract just the detection of some particular movements and not having to deal with raw data: what algorithms can be useful in this case? What statements? Is there some C++ library that I can dissect to get some useful info?


Would you suggest the use of an heuristic algorithm?




lighting - How does Minecraft render its sunset and sky?



In Minecraft, the sunset looks really beautiful and I've always wanted to know how they do it.


Do they use several skyboxes rendered over eachother? That is, one for the sky (which can turn dark and light depending on the time of the day), one for the sun and moon, and one for the orange horizon effect?


I was hoping someone could enlighten me... I wish I could enter wireframe or something like that but as far as I know that is not possible.


enter image description here



Answer



I'm going to gamble on the fact that you really want to know how to achieve a similar effect, and not specifically how Minecraft does it, which wouldn't be an on-topic question.



Do they use several skyboxes rendered over eachother? That is, one for the sky (which can turn dark and light depending on the time of the day), one for the sun and moon, and one for the orange horizon effect?



You don't need that much geometry -- a single skybox and some geometry for the sun/moon is sufficient. Skyboxes are generally rendered in such a fashion as to ensure they are always the same distance from the eye, thus giving them the "infinitely far away" effect. The same thing can be applied to the geometry for the sun and moon, except you'll also want to transform the sun and moon by some global time value.



That same global time value feeds in to the skybox effect, which can be done with a shader that modulates between day and night textures (or just colors if you want to be simple) based on the time.


To get the "orange glow" on the horizon you'll want to also modulate in some vertex (or pixel) colors on the textures. Atmospheric scattering and perspective play a large part in determining these effects in the real world, and several papers exist presenting various ways of simulating those variables in software. The paper A Practical Analytical Model for Daylight is one I've personally used and implemented (dead image links there, you'll want to make sure you get the PDF on the linked site).


The Virtual Terrain Project has a section of curated links to relevant papers as well.


word choice - "I have sent it to X too" vs. "I have sent it to X also"



  • I have sent this e-mail to Aman also.


  • I have sent this e-mail to Aman too.


Which one is correct? What is the exact difference between the two? Please explain.



Answer



In the context you are asking about, the two words are very synonymous, so there is no "exact difference" between the two.


When I am choosing one over the other, my choice is often based on style, and how they sound. For example, in this sentence, I would use also, simply because it sounds better (who wants to say "two-too"?):



When I asked if they wanted a slice of bread, Jim asked for two, and Jane asked for two, too.
When I asked if they wanted a slice of bread, Jim asked for two, and Jane asked for two, also.




Moreover, this is a generality, but I think also usually sounds better in technical writing; it seems slightly more formal:



The graph shows that the function f(x) is continuous, and g(x) is continuous, also.



At the beginning of a sentence, also just about always the better word:



Also, I sent this email to Aman yesterday.



However, at the end of a sentence, when you're indicating "as well", there's really not much difference in which one you use (although a comma is generally used before too in this context):




I have sent this e-mail to Aman also.
I have sent this e-mail to Aman, too.



tiles - 2D Top down view maps



I was wondering how this works.


Do you load the complete map when the game starts up, or do you load parts of the map at runtime?


And how would you save the maps? Would it be in XML or some binary format?


Thanks!



Answer



I agree with eBusiness. It depends on the size and how you want to edit it.


Estimate the byte size of your map in a reasonably compact representation. Also decide which parts of the map can change as the game plays. Those parts that don't change can be loaded and don't have to be saved. If the estimated size is small, just store everything in memory. It's not worth the extra complexity of loading parts of the map and tracking what you've loaded or not, unless the data is so large that it's necessary.


For example if you were writing Civilization II, your map size might be 100x100 tiles.



  1. Each tile is one of 12 types, so you can store that in 4 bits. That means the main map is 100 x 100 x 0.5 bytes = 5,000 bytes to store the tile types. The main map never changes.


  2. You can also improve map tiles with roads, irrigation, etc., and there are up to 7 improvements. That means 2^7 different values, taking 7 bits, but we'd probably just use 1 byte for it. That give us 100 x 100 x 1 byte = 10,000 bytes to store the improvements.

  3. The fog of war tells us which map tiles you've seen, so you need 1 bit per player. If you limit to 8 players, that's another byte per map tile, or 10,000 bytes for the fog of war.

  4. Finally, there are all the cities and units. You might estimate that each player has up to 20 cities and 100 units, and each of these might require 100 bytes of data (wild guess), so that's 12,000 bytes (much more if you're using XML).


That's under 30k for a compact binary representation the Civ II map + objects, so you can store all of it in memory, even if you use a verbose format that's much larger. I got the above numbers from someone reverse engineering the Civ II map structure.


Daggerfall, considered by some to have a ridiculously large map, appears to be 5000x2500 and around 25 megabytes, but it also has a large number of NPCs (750,000 is what I've read but that seems very high). On today's desktop/laptop machines this too could fit into memory, but on mobile devices or browsers that might be a bit too big. There's a wiki describing the Daggerfall map format.


You can reduce the size by identifying and factoring out redundancy. For example, instead of storing 100,000 identical trees or swords each in an XML format, store one tree and one sword and 100,000 references to them. In the binary formats that reference might be only 1 or 2 bytes, and in a more verbose format the reference can still be reasonably small.


Do the simplest thing that works for your game. If the map is small, it doesn't matter if you use a compact or verbose format. If the compact format would fit into memory but the verbose format would not, you have to decide whether the extra work of the binary format is more or less than the extra work of loading portions of the map. That'll depend on the game. In a Civ-like game where you need all the data to simulate turns, the binary format is probably a better choice. In a Daggerfall-like game where you don't need to load areas except what's near the player, loading portions of the map is probably a better choice. If the map is so big that even the compact format won't fit in memory, then first ask yourself if it's really worth all the extra work to deal with it, and if so, design a binary format that you can load portions of.


For my current (hobby) project, the maps and all the objects on them fit into 50 MB, so keeping it all in memory would be fine. However, I want it to run in the browser, and 50 MB is more than I want to transfer over the network, so I'm keeping them all in memory on the server and then loading only parts of the world in the client. My map tiles are 1 byte per tile, 2048x2048 tiles (4 MB). The objects (trees, chairs, orcs, etc.) are JSON-encoded for simplicity. In the client I only load the map areas (including their objects) that are near the player.


Wednesday, April 27, 2016

complementation - that looks an interesting book; they look good guys



That looks an interesting book. (OALD)



Look’ can take an NP for its complement by OALD. Now what I’m wondering about is if a person/people could be a subject in the structure, for instance, “They look good guys.” If we can’t, does it have to be “They look like good guys”?



Answer



As some comments indicate, omitting the preposition in constructions of the basic form "X looks [like] Y" (where X is a noun, not an adjective) seems to be less acceptable in AmE than BrE.


As a Brit, I have no problem with OP's example. In his 1951 novel The Masters, the English chemist and novelist C P Snow wrote...




At a first glance, people might think he looked a senator.



Since C P Snow would definitely be considered a competent writer, I think we can dismiss concerns that the usage is "ungrammatical" in any meaningful sense. And leafing through the results in Google Books for "looks a safe bet" I see several that are unquestionably AmE sources. For example, this is from an American book about baseball...



...it looks a safe bet that Comiskey will have a regular soldier drilling the Sox at their Texas camp.





Comparing US/UK corpuses in Google NGrams for to look a picture, I can't see much evidence of a usage split. And Google Books claims 89 instances of "You do look a picture" (I included do to ensure most/all instances were relevant to the usage under consideration), but there are no written instances at all of "You do look like a picture".





TL;DR: You will encounter some native speakers (particularly, Americans) who have misgivings about the usage in general. But I think even many of those people would be more accepting of my safe bet/picture examples than they would of OP's particular version. It's more a matter of what you're used to hearing, rather than a specific point of "questionable" grammar.


java - Moving the jBullet collision body to with the player object


I am trying to update the location of the rigid body for a player class, as my player moves around I would like the collision body to also move with the player object (currently represented as a cube). Below is my current update method for when I want to update the xyz coords, but I am pretty sure I am not able to update the origin coords? :


    public void Update(float pX, float pY, float pZ) {
posX = pX;
posY = pY;
posZ = pZ;

//update the playerCube transform for the rigid body

cubeTransform.origin.x = posX;
cubeTransform.origin.y = posY;
cubeTransform.origin.z = posZ;

cubeRigidBody.getMotionState().setWorldTransform(cubeTransform);

processTransformMatrix(cubeTransform);
}

I do not have rotation updated, as I do not actually want/need the player body to rotate at all currently. However, in the final game this will be put in place.




Answer



You need to make the physics object a kinematic object. See Bullet Physics Manual for more information. Bullet Physics ask every frame the current transformation from kinematic objects. You need your own MotionState implementation for that. Mine is as simple as this:


public class KinematicMotionState extends MotionState {
private Transform worldTransform;

public KinematicMotionState() {
worldTransform = new Transform();
worldTransform.setIdentity();
}


@Override
public Transform getWorldTransform(Transform out) {
out.set(worldTransform);
return out;
}

@Override
public void setWorldTransform(Transform worldTrans) {
worldTransform.set(worldTrans);
}

}

In addition you must tell the rigid body that it's a kinematic object:


rigidBody.setCollisionFlags(rigidBody.getCollisionFlags() | CollisionFlags.KINEMATIC_OBJECT);
rigidBody.setActivationState(CollisionObject.DISABLE_DEACTIVATION);

And then updating the transformation of the kinematic object:


Transform transform = new Transform();
transform.setIdentity();
transform.origin.set(x, y, z);

motionState.setWorldTransform(transform);

Tuesday, April 26, 2016

image - Storing a hex grid


I've been creating a small hex grid framework for Unity3D and have come to the following dilemma. This is my coordinate system (taken from here):


enter image description here


It all works pretty nicely except for the fact I have no idea how to store it. I originally intended to store this in a 2D array and use images to generate my maps.


One problem was that it had negative values (this was easily fixed by offsetting the coordinates a bit).


However, due to this coordinate system, such an image or bitmap would have to be diamond shaped - and since these structures are square shaped, this would cause a lot of headaches even if I hack something together. Is there anything I'm missing that could fix this? I recall seeing a forum post regarding this in the unity forums but I can no longer find the link.


Is writing a set of coordinate translators the best solution here?


If you guys think it would be helpful, I can post code and images of my problem.



Answer



The parallelogram coordinates you're using are easier to work with, but they do have the drawback of being weird for rectangular maps. One approach is to store it with the offset coordinates but actually use parallelogram coordinates in your game logic.



Observation: in each row of the map, the grid data is contiguous. All the wasted space is on the left and right.


Solution: within that row, store data starting at the leftmost column instead of the column marked 0. Calculate the first column of the rectangular map in your coordinate system, then subtract that from the column coordinate to determine where in the array it goes. This works for negative column coordinates too.


Perform the conversion in the getter and setter for the map, with something like this:


inline function get(q, r) {
first_column_in_this_row = -floor(q/2);
return array[r][q - first_column_in_this_row];
}

You'll have to modify this to work with your choice of coordinates and map (pay attention to off by one differences). In some layouts you'll want to offset the columns by the row instead of vice versa.


You can use the same trick to make maps of other shapes; it's not limited to rectangles.



If you're using C or C++ you can use pointer arithmetic to make this faster. Instead of storing an array of pointers to arrays, store an array of pointers that have been adjusted by first_column_in_row. (This may not be portable)


graphics - How do I make a progress bar with letters that get "filled in"?



I want to make a progress bar made of text! I have two images: One with the text in gray, the other coloured:


gray progress bar colored progress bar


As my game is loading, I want the letters to "fill up" with color:


filling-up progress bar


They would start out gray, then fill in.


I was thinking of overlaying a transparent rectangle over the gray image, then stretching the transparent rectangle to match the progress. But then the background will be coloured too. I want only the letters to be coloured!


How can I do this?



Answer



I don't know how this feature would be implemented in your specific development environment, but the solution to the problem you describe is masking.


Basically, apply a mask to the progress bar in the shape of your letters and then the stretched rectangle won't be rendered outside the mask.



Monday, April 25, 2016

rendering - Is there any heuristic to polygonize a closed 2D raster shape with n triangles?


Let's say we have a 2D image black on white that shows a closed geometric shape.


Is there any (not naive brute force) algorithm that approximates that shape as closely as possible with n triangles? If you want a formal definition:



Approximate the shape with a polygon that when rendered into a new 2D image will match the largest number of pixels possible with the original image.




Answer



I think you'll need to do it in two or three steps:


For converting a raster image to polygons you can use pre-existing software like http://en.wikipedia.org/wiki/Potrace



Optimizing the result from that to get the best possible result with a specific number of polygons I believe is much harder. However efficiently optimizing an existing mesh down to a lower poly count isn't too difficult if you don't care about the result being optimal. For example http://research.microsoft.com/en-us/um/people/hoppe/proj/meshopt/ describes one algorithm to optimize a 3D mesh, based on a parameter saying how much to optimize it.


Once you have that optimized mesh you could apply a hill climbing algorithm to the vertex positions to try to further improve the fit.


camera - FPS games: don't they have unrealistic one-eyed view? What are the causes?


I have played many fps games, and noticed that the camera perspective is similar to the 'one eyed view' of the surroundings. It does not feel like bilinear. :/


Is it because of the single flat view of the screen? Or is it the problem that can be fixed by some research?



PS: If you want, try to roam around with only one eye open.



Answer



I'll state the obvious - FPS games are doing the best they can within the limitations of a single 2D display device.


The interesting part - this might change soon thanks to the Oculus Rift project - a VR headset for games. I've seen info that DOOM 3 is fully supported (due to Carmack's involvement) and that Hawken has promised support. There is also work on external engine integration (Unity and Unreal were mentioned here).


Note the games on Oculus must support full stereoscopic 3D, since the headset has a separate display for each eye.


Sunday, April 24, 2016

terminology - What exactly A flap is in the context of a cardboard box?



per this answer



The bits at the top and the bottom that tuck in to seal the box are called the flaps.



are there 4 flaps in the image shown below?


enter image description here


or the whole top is A flap?


Are these 4 parts also flaps?


enter image description here


My concern is if only the part that could be tucked in called flap, because I had got this answer (exactly the same one at the beginning of this post) originally.




The bits at the top and the bottom that tuck in to seal the box are called the flaps.





Adverb usage: tight/tightly


I'm new to English. Could anyone tell me what is wrong with the first statement?




  1. She held the bag tightly, even her arm hurt badly.

  2. She held the bag tight, even her arm hurt badly.  (Correct one according to a source)



Answer



Sentence 1 uses the word tight correctly.



She held the bag tightly, even her arm hurt badly.



You need to add "ly" on tight to make it an adverb. The word "tight" is describing her hold on the bag—not the bag. Holding is a verb, so an adverb should be describing it.





However, the rest of the sentence is not correct. It should be either separated into two or the second part changed to a dependent clause.


These both work:



She held the bag tight. Even her arm hurt badly.




She held the bag tight, even though her arm hurt badly.



Edit: As the other questions point out, "tight" can also be an adverb. As a native speaker, using tight as an adverb sounds a little odd, but both sentences are correct.


Is there a word or slang word to call a girl who loves brand products?


Is there a word or slang expression for girls who are preoccupied with materialistic things, such as bags, rings, necklaces and so on, and with showing such things off to others?


Girls for whom superficial appearance is more important than internal qualities.



Answer



The word "poser" comes to mind.



There are a few words and phrases that generally mean this sort of thing but usually they refer to a specific aspect. Someone who overly values worldly possessions would be "materialistic" but a materialistic person may or may not have the motivation to show off those possessions. They may simply be a hoarder or even secretive about their possessions.


Someone who likes to show off could be "vain", "pretentious" or compensating for insecurities but that may also apply to someone who pulls stunts for attention or someone who tries to "win" every conversation.


"Shallow" is another broad term that encompasses most of what you describe.


Saturday, April 23, 2016

mathematics - How do I calculate the total XP to reach a particular level, when each level takes 10% more?


How do I calculate the amount of XP for a level where the first level is 110, and each level after is 10% more than the last. Preferably to do without a loop because the levels will have to be infinite and will need to be quickly calculated.


in js using a loop:


var xptest=110;
var lastLevel = 110;

for (var level = 2; xptest <= Number.MAX_SAFE_INTEGER || level < 100; level++) {

lastLevel*=1.1;
lastLevel = Math.round(lastLevel *1.1)
xptest+= lastLevel;

console.log('LEVEL',level,'('+lastLevel+' / '+xptest+')');
}

Answer



Let's work through some cases, given \$baseXP = 110\$ and \$increase = 1.1\$:



$$\begin{align} targetXP(1) &= baseXP\\ targetXP(2) &= baseXP + baseXP \cdot increase\\ targetXP(3) &= baseXP + baseXP \cdot increase + baseXP\cdot increase^2\\ ...\\ targetXP(n) &= baseXP + baseXP \cdot increase + ... + baseXP \cdot increase ^ {n-1}\\ \end{align}$$


If we multiply \$targetXP(n)\$ by \$increase\$, we find that all it does is shift the terms down one:


$$\begin{align}targetXP(n)&\cdot increase\\ &= baseXP \cdot increase + baseXP \cdot increase^2 + ...+ baseXP \cdot increase^n\end{align}$$


So if we subtract the original from this shifted version, all the terms except the first and last will cancel out, and we get...


$$\begin{align} targetXP(n) \cdot increase - targetXP(n) &= baseXP \cdot increase^n - baseXP\\ targetXP(n) \cdot (increase - 1) &= baseXP \cdot (increase^n - 1)\\ targetXP(n) &= baseXP \cdot \frac {1 - increase^n} {1 - increase}\end{align}$$


This is what's called a Geometric Series - you can read more about the math behind this here.


discourse context - It Happened That, As It Happened


Is there a difference here:




  1. It happened that he did not go to work today.

  2. As it happened, he did not go to work today.




Do "it happened that" and "as it happened" have different meanings?




game maker - How to make a more accurate lap time? get_timer() LIMITATION?



In the room there are 22 cars. All cars have a different speed.


The cars are numbered from 1 to 22 with the help of the variable carNumber.


CODE - obj_Car / Set car speed (Create Event):


velocity=10-((carNumber-1)*0.01);



Here's how there is a difference in car placement near the end of the lap:


enter image description here




However, even with this difference, the times of many cars are repeated:



enter image description here




The detection of lap time looks like this.


CODE - obj_Car / Time lap (Collision with obj_Finish) :


other.orderLapTime[car]=get_timer()-other.discount;




  • Discount = this is the exact time when the room starts (cars already start running).



CODE - obj_Finish / Set discount (Create Event):


discount=get_timer();



The display is made with a modifier (multi, to simulate actual track times).


CODE - obj_Finish / Draw time lap (Draw Event):


draw_text(1500,100+(20*(i)),string_format(orderLapTime[i]*obj_Seth.multi/1000000,1,3));



Even taking the multiplication and increasing the number of decimal places, there are still many repeated times:



enter image description here


Some inconsistencies including. Cars with slower speeds marking faster times.




I could slow down the base speed (10) to solve such a problem, but I already think in the long run. The races can't take so long. In addition I intend to give the player the option to set the speed with which the race takes place (a multiplier, more frames, etc).


It could also increase the difference between the speeds (0.01 to 0.05), but I would like a general resolution, so that I can notice through the lap time, if only by one thousandth (0.001).




EDIT 1 - Attempts made based on answers and comments from Bálint and TomTsagk:


That is what I tried to do.


CODE - obj_Car / lap time (Step Event):


unit+=velocity/60*0.001;


Below the results...




enter image description here


Respective code:


draw_text(1500,100+(20*(i)),string_format(orderLapTime[i],1,3));



enter image description here


Respective code:



draw_text(1500,100+(20*(i)),string_format(orderLapTime[i],1,5));

The speed difference between the cars is 0.01.



Answer



The solution I found, you should count the time using the step event at the finish line.


obj_Finish - step event:


timer+=1;

And when the car collides with the finish line, just add to the timer result the distance between the origin of the car and the origin of the finish line.


obj_car - colision with obj_finish:



distance=point_distance(x,y,other.x,other.y);
lapTime=other.timer+distance/10;

That way, even if multiple cars with different speeds collide with the finish line in the same frame, the distance from each to the finish line will be different, so the time will be different.


The division by 10 made the calculation value correct, so that I could order the cars..


meaning - Is it common to describe "Be going to" form as Simple Future?


"Be going to" form is called Simple Future in some English Grammar websites and books.



Simple Future has two different forms in English: "will" and "be going to" English Page





The Simple Future Tense has two different forms in English, will and be going to. Contextual English



I had discussion with a very good English user (I don't know if she is a native speaker or not) about this form. and she said she had never heard of "Be going to" described as Simple Future.


So, Is it common to describe "Be going to" form as Simple Future?



Answer



This one is tricky because you need to remember to conjugate the verb. Technically, it is "to be going to". But yes, they are mostly interchangeable. For example, the following two sentences have the same meaning:



I am going to have my car fixed tomorrow.


I will have my car fixed tomorrow.




But it is incorrect to say:



I be going to have my car fixed tomorrow.



In this example, the verb to be has not been conjugated.


future tense - "Will" vs "going to" vs present continuous


Would you please tell me which tenses are suitable here?




... the sun (KEEP) burning forever?


Sometime in the next twenty-five years, a spaceship with a human crew (LAND) on Mars.



My grammar book gives only two options: "to be going to + verb" and "will + verb". But I wonder the reason why I should avoid using the "continuous present" tense.



Answer



In terms of future events, the present continuous indicates an event that will happen in the near future, so



"A spaceship with a human crew is landing on Mars tomorrow"




works, but



"Sometime in the next twenty-five years, a spaceship is landing on Mars"



is just too far removed from the present.


Remember that the PrC connects to the present - if you say they are landing tomorrow, we can imagine that right now, in the present, they are making the preparations towards performing and completing that near-future action (note: "they are landing tomorrow" does not in itself mean "they are preparing now" - the present state is simply implied).


When you say "In the next 25 years" (and especially with the vague "sometime"), the point of completion is entirely in the future - so far in the future, that it is difficult to imagine the connection to the present at all.


Of course, PrC can be used for a longer action in the present that will have consequences in the future. In this case, you would say



"They are preparing to send a spaceship to Mars",




even though the actual sending might be 25 years in the future.


As for "the sun is burning forever", "forever" includes the present of course, but it also points way, way into the future - and of course indicates that the action will never be completed. "I am studying nursing" works because completion will occur in the near future, and there will be an effect of the present action in the near future.


You can say "The sun is burning today", but of course the burning of the sun now does not indicate its state of burning in the distant future (grammatically speaking).


EDIT: As Nico points out, if you want to use "keep", this will not work with PrC: one would not formally say "The sun is keeping shining".


Friday, April 22, 2016

american english - a fighting for the glory - how do you understand this type of grammar?


A stanza from a song called John Paul Jones by Johnny Horton:




When John Paul was a captain in the U.S. Naval Band
A fightin' for the glory and the freedom of our land
He made those British captains wish that they were on dry land
He sent their mighty vessels to the bottom of the sea
He took their bags of treasure and he sank their chests of tea
He gave his blood for all free men and his life for liberty



The only thing I know is that this type of grammar is usually only used in old songs and poems, but I don't think I know how to actually understated it. I asked an American friend of mine, but he couldn't give me a definitive answer as to how one should understand it, only that this is some kind of manner of speech that's mostly used in old poetry and songs.



Answer



The "a-" prefix is not part of standard English grammar. It is used in some dialects of English (especially the American South, I think) with progressive present verbs that end with -ing. In my experience, it does not provide any extra meaning.



It is usually written a prefix with a hyphen (not as a separate word): He's a-runnin', She's a-comin', We come a-wassailing, etc.


Here's a high-level answer from ELU: The times they are a-changin'


One answer on ELU suggests this a corruption of an Old English construction, in which on was used to make a verb progressive:. In Old English (hundreds and hundreds of years ago), present verbs were not progressive unless prefixed by "on": "the times change" versus "the times are on changing."


This is certainly consistent with the fact that "a-" prefix is only used with progressive -ing present participles. In modern usage, I think it is used purely as an intensifier or to help the meter in poems or songs. (However, I don't speak a dialect of English that uses the prefix normally, so I'm not 100% sure.)


sentence structure - "How is this called" vs "What is this called"?


Which of the following is more suitable as a title for a picture with an arrow toward a part of the body's anatomy?




  1. How is this called?

  2. What is this called?



I need this for a picture of a part of the body, that appears without information about this part. So, I need to ask what it is called in anatomical terminology.



Answer




In American English, it's definitely "What is this called?".


"How is this called" is a common mistake with second language learners. If this phrasing is used, it will signal to any native speakers viewing the diagram that it was created by a learner.


In the Google nGram data, "How is this called" doesn't even appear.


android - Implementing a basic jump in libgdx


I have seen the document for libgdx and managed to move the character and also to implement bounds but the document does not show how to implement jumping.


I have downloaded the superjumper demo code but it is too confusing for me. Is there anyone here who can guide me?


Say for example we have a spritebatch:


Spritebatch batch;


How can I implement a jump for this spritebatch when the screen is touched?



Answer




NOTE: Apparently, in libgdx, the origin is at the lower left corner of the screen. You should switch "IncreaseYCoordinate" with "DecreaseYCoordinate" in your actual code.



Jumping, at the base, is language and framework agnostic. You should look at it that way if you wish to learn anything. "Jumping", especially in 2D games, is the process of modifying a character's (sprite's) position on the screen so that he or she appears to be jumping. That's all. You just draw your character at a different height on each Draw call, so it appears to be moving vertically (jumping).


I'm not exactly familiar with libgdx, but I presume you're doing something like:


batch.draw(someTexture, 100, 350); 

Where 100 is the X coordinate and 350 the Y coordinate of the drawn texture. This obviously makes your texture show up at the position described by the vector (100, 350). I am currently supposing that the origin (0,0) is the upper left corner of the screen (increasing the Y coordinate makes your sprite show up lower on the screen).



Now, if you were to decrease the Y coordinate, like:


batch.draw(someTexture, 100, 349);

Your texture would get drawn at a higher position on the screen.


batch.draw(someTexture, 100, 348);

And even higher, now.


Simple, is it not? The first thing you need to do is to get your sprite to continuously ascend until he should stop doing so. Then, the sprite should go back to its original position by descending. Since you have not posted any actual code, and the question is a bit broad, I can only give some rough guidelines.



  • Store your sprite's position in a Vector-like structure. Or two variables, one for the X coordinate, and one for the Y coordinate.


  • The jump should go smoothly. Keep two variables: "speed" and "originalSpeed". These should be integers;

  • Keep a state flag, that tells the Update() function when to increase or decrease the sprite's Y coordinate. This can be an enum with the values { Ascending, Descending, Standing }

  • Intercept the touch event, and when it happens, set the state flag to Ascending (if it's not already set to Ascending);


  • In the Update method, you should change the Y coordinate of the sprite considering its current state. Thus:


    if (State == Ascending) 
    {
    //We're ascending. Decrease the Y coordinate of the sprite by the speed.
    DecreaseYCoordinateBy(Speed);
    DecreaseByValue(Speed, Value); //The character needs to jump smoothly, so the speed should decrease as he ascends.

    if (Speed <= 0)
    {
    ChangeState(Descending); //If speed is <= 0, then the character should fall down.
    Speed = 0;
    }
    }
    else if (State == Descending)
    {
    //We're descending. Increase the Y coordinate by the speed (at first, it's 0).
    IncreaseYCoordinateBy(Speed);

    IncreaseByValue(Speed, Value); //Increase the speed, so the character falls gradually faster.
    if (CurrentYCoordinate >= OriginalYCoordinate)
    {
    //If we reached the original Y coordinate, we hit the ground. Mark the character as standing.
    ChangeState(Standing);
    CurrentYCoordinate = OriginalYCoordinate;
    Speed = OriginalSpeed;
    }
    }



  • Drawing is done like:


    batch.draw(yourSprite, CurrentXCoordinate, CurrentYCoordinate);


Obviously, you need to enter your own values for the original coordinates and speeds. Tweak them to find the values that best suit your needs. This is not exactly the "best" way to do it, but should give you a starting point. You may want to impose some limitations on the falling speed, so that it increases only up to a certain amount. You could (and should) use different speeds for jumping and falling too.


Also, this is not libgdx related, but might give you a few hints:


http://www.xnadevelopment.com/tutorials/thewizardjumping/thewizardjumping.shtml


I definitely recommend that you search for as many such tutorials as possible, even if they're not libgdx related. Jumping is a concept that can be learned from just about any source.


.net - What C# libraries can be used to support game development?



As games are based on many different subsystems things like graphics (DirectX, OpenGL, ...), sound (OpenAL, Ogg Vorbis, ...) or physics (collisions, ...), what libraries do you know that are useful for game development in C# and what benefits do they offer?



Answer



Graphics/Sound



  • XNA High level wrapper on DirectX9. Allows you to get up and running quickly. Supports PC, Xbox360 and windows phone 7. Support Xact audio aswell as its own SoundEffect API.

  • SlimDX Lower level wrapper on DX9/10/11. If its in the DX SDK, its wrapped here.

  • OpenTK Wrapper on OpenGL/AL.

  • SDL.net A port of thr popular SDL lib.



Engines



  • WaveEngine Component based game engine architecture, C# api, 2d and 3d physics engine, beautiful visual effects, cross-platform support Android, Linux, Mac, iOS & Windows, advanced layout system and much more.

  • NeoAxis A 3D engine with support for NVIDIA PhysX physics engine, C# bindings, supports WPF & Windows Forms, rich selection of tools like map, object, model, material, terrain editors, in game browser using Chromium, Pathfinding with Navigation Mesh and more.

  • TorqueX A 2D/3D engine for XNA. Good editor suppport, garage games have recently reinvested in the engine after a period of neglect.

  • truevision 3d C++ game engine with c# bindings

  • Axiom A rewrite of Ogre in c#. Supports numerous backed rendering APIs.

  • Unity is a C++ graphics/game engine that supports gameplay scripting in C#

  • AngelXNA A port of EALA's open source angle protoypeing framework



Physics



  • Farseer A popular 2D physics engine, supports .net(desktop), compact(xbox) and micro(silverlight).

  • Jitter a relatively new 3D physics engine, Much better than its completion.

  • Box2Dx A direct port of box2D

  • Box2D.XNA Another port of Box2D for XNA; more recent than Box2Dx

  • JigLib

  • BulletX A c# port of Bullet, seems to be abandoned.



Thursday, April 21, 2016

lighting - What does it mean to "bake lights"?


What does it mean to bake lightmap ? I heard this in Unity3d, and again found this LightUp plugin for sketchup that bakes lightmap.


From what I observe, the lightmap baked gives the 3d object a much more realistic feel. Is the purpose of baking light on object to give that cg animation look you see on pre-rendered animations?



Answer



When you have a static (non-moving) light in a game, you have two options for rendering this light. You could render it the same as a dynamic light; that is, feed it through the shader pipeline which will calculate its effect on everything around it, every frame, on its way to the screen. This is obviously pretty expensive. Or, an editor can bake the light into the scene.


What I've always thought of baking was perhaps a more simple version: basically the editor just takes the textures of everything around the light, calculates the effect of the light on those textures (brightens them, perhaps colors them, shadows, etc.), and saves them as replacement textures to use. So all the textures around the "light" look like they have a light cast on them, but at runtime there actually isn't a light from a calculation standpoint; it's an optical illusion, essentially.


Unity, however, seems to be generating a lightmap. This is similar to the above notion, but the baked lighting is kept separately instead of modifying the underlying texture, and I assume a shader merges the two at runtime. This would have the advantage of keeping the advantage of tiled textures (i.e. low memory usage), since they wouldn't have the light baked right into them therefore they could remain tiled, and the shader would be very lightweight, especially compared to treating the light as dynamic.


A light obviously needs to be static for this to work; that is, you can't move it during gameplay, because the light has been baked into the textures. Also, any dynamic objects in the room (such as the player character) won't have the light shining on them so there needs to be some sort of exception, where the light is rendered for dynamic objects but not (re-)rendered on the static scenery.


grammatical number - "No more Hiroshima" or "No more Hiroshimas"


"No more Hiroshima" or "No more Hiroshimas". Some say the former and some say the latter. I'm wondering which is grammatically correct.




possessives - What is the use of using preposition 'of' to talk about possessions with *ANIMATE* countable nouns?


In the coursebook 'New Round-Up 3' by Virginia Evans, Jenny Dooley and Irina Kondrasheva (Pearson, 2010) I have come across a title "A Day in the life OF a Farmer'.


Michael Swan in his fully revised 'Practical English Usage' (third edition, OUP, 2013) says that 'we use the 's structure most often to talk about possessions, relationships and physical characteristics, especially when the first noun refers to a person or animal, or to a country, organisation or other group of living creatures'.


My question is: will it mean the same if we used 's with it?



Answer



Aleksandr Solzhenitsyn wrote the novel: Оди́н день Ива́на Дени́совича.


It has always, to my knowledge, been translated as:


A) One Day in the Life of Ivan Denisovich


which, as others have already answered, is perfectly natural and idiomatic in English. A day in the life of is indeed quite common, so common it can be considered a fixed phrase.


Else, you would have:



B) One day in Ivan Denisovich's life, or even, word-for-word, One day of Ivan Denisovich's.


which do not have the same ring (rhythm) or zing (energy) to it. The idiomatic title (A) has a rhythm to it and English has a certain rhythm, or series of stress points, built into it. One can clap one's hands to many English sentences. And if the choice is between a title or construction that is rhythmic and one that is lesser so, a wise publisher will go with the former.


Else, you also have:


C) A Day in a Farmer's Life.


Which sounds just so bland in comparison to the 'normal' way of formatting the phrase. It is so uninteresting a title (and phrase) that I might not even look at the book if I had the choice of others to look at.


In other contexts, the pattern could stress whose thing, for example, whose answer it is:


If I say, (D) rogermue's answer, I am using the name as an adjective and thus am not really calling attention to the fact that it is (E) the answer of rogermue, which somewhat calls attention to the fact that rogermue (and not someone esle) wrote the answer.


Last, notice the definite article in the preferred phrases (B) and (C) and the specialized phrase (E): the adds a certain punch in the phrase. We know we are talking about a specific life or a specific answer. It is hard to explain what the little the does there, except to say that perhaps we all prefer to read about the life or read the answer rather than about a life or so-and-so's life or so-and-so's answer.


Wednesday, April 20, 2016

animation - How do I interpolate around a rectangle?


I want to make a fancy animation where a point travels around a rectangle. I want to find the point's position at a time t.


The rectangle is given by X, Y, Width and Height.


a rectangle, with a clockwise path around it


Is there an algorithm for this?


I've used sin/cos for circles. What's the equivalent approach for rectangles?



Answer



I'll assume your t goes from 0 to 1. (If not, just multiply to scale it appropriately.)



rectangle interpolation


Figure out what proportion (01) each side is of the perimeter. (side length / total perimeter)


To find how much of every side is “filled in” at time t, iterate through sides, subtracting their proportions until t is depleted to a negative value. That last edge (which caused t to go negative) is filled by a proportion of (side length + remaining) / side length. The rest are not filled.


To get the exact vector position at t, multiply each side's vector by the proportion of that side that is filled, and add them.


This works for any polygon actually!


arbitrary polygon interpolation


singular vs plural - Two-year program or Two-years program?



Which is correct, a "two-year" program or "two-years" program?


The difference between two expressions is the absence/presence of "s", i.e., singular or plural.



Answer



When we use counted elements as adjectives, they take a hyphen and lose the plural ending -s, because adjectives don't have plural forms in English:



Here are some examples:


a two-year program, a 3-day hike, a two-hour test, a four-year-old child, a 100-year war


singular - Can I use plural nouns in table headings?



I've always thought that table headings need to be singular. However, I've come across examples when that hasn't been the case.


For example, if there is a table that shows the number of visits that each store had in a year from all over the country, the heading (the first column) that lists stores would be "Store," but the heading (the second column) that lists the number of visits would be "Visits" instead of "Visit."


What would be the rule to follow?




Tuesday, April 19, 2016

xna - How can I use a camera matrix with different resolutions?



I created a little jump'n'run game. The character(Mario) is always the center of the viewport. The game is running correctly if I use the resolution 800x480 pixel. But when I use another resolution(for example 1280x768), the sprites in the viewport look completely different to the sprites in the 800x480 viewport. I want that the viewport(and the sprites in the viewport) looks always the same, on every single resolution.


How can I do that? Should I change something on my camera matrix parameters or what should I change so that the viewport and the proportions of the sprites look always the same?


I use Monogame to run the game on different Windows Phone devices.


My camera class:


 public class Camera 
{
public Vector2 Cameraposition;

public Camera(Vector2 cameraposition)
{

Cameraposition = cameraposition;
}

public void Update(GameTime gameTime, Vector2 CamPosition)
{
Cameraposition = CamPosition;
}

public Matrix GetMatrix()
{

return new Matrix(1, 0, 0, 0, 0, 1, 0, 0, Cameraposition.X, Cameraposition.Y, 1, 0, -Cameraposition.X, -Cameraposition.Y, 0, 1);
}
}

In Game1:


//I use the camera in Game1 like this:
//At the beginning(in LoadContent):
Vector2 cameraposition = new Vector2(PlayerStartpos.X - GraphicsDevice.Viewport.Width / 2, PlayerStartpos.Y - GraphicsDevice.Viewport.Height / 2);
camera = new Camera(cameraposition);


//Updating the camera position
protected override void Update(GameTime gameTime)
{
player.Update(gameTime);
Newcameraposition = new Vector2(player.Playerposition.X - GraphicsDevice.Viewport.Width / 2, player.Playerposition.Y - GraphicsDevice.Viewport.Height / 2);
camera.Update(gameTime, Newcameraposition);

base.Update(gameTime);
}


//Drawing:
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, camera.GetMatrix());
...

Answer



Your question is not an exact duplicate, so I won't try to close it. But it's close enough that I feel comfortable in simply sending you over to my old answer on Supporting Multiple Resolutions.


That answer is specifically for the XNA Platformer Sample, so you should probably download a copy of that to play around with to get a feel for how the code in my answer works. Then you can apply it to your own game.




Note, in particular, how I use matrix multiplication to combine two matrix operations, as mentioned in comments on your question:


Matrix camera = Matrix.CreateScale(scale, scale, 1)
* Matrix.CreateTranslation(translateX, translateY, 0);

capitalization - the Capital and Small Letter in Title


I am confused about when to write capital letter or small letter in a title. Like the title above, I think



The, and, in are perp, so they can be small letters.



Am I right? Can someone clarify the rules about the Capital and Small Letter in Title.



Answer




Very interesting question. Nevertheless, it's debatable as well. Some writers prefer to capitalize some words whereas others don't.


Let's look at a few points here -



a) Prefer capitalizing the first and last word of a title.
b) Avoid capitalization if it's scientific name or botanical name for the second word. For instance - Asparagus racemosus.
c) Capitalize all adjectives, most of pronouns, nouns and adverbs. Capitalize verbs as well if you want to emphasize them.
d) Try avoiding capitalization of very short words (conjunctions?) such as and or or. Also be, are, was, were, as, to, and so on [This is debatable in particular].
e) Avoid capitals to the definite and indefinite articles
f) Capitalize all the words if they are of five or more letters.




More information here.


modal verbs - using "should" in an if adverbial clause



Do any one know if we use the word should in any if adverbial clause, so how that affects the sentence? Just my Profs. told me this: when we add "should", this emphasises the speaker's uncertainty that something will happen.


Take for example.



I'll be at my uncle's house in case you should need to reach me.




Answer



All of these mean the same thing:



I'll be at my uncle's house in case you should need to reach me.


I'll be at my uncle's house in case you need to reach me.



I'll be at my uncle's house if you should need to reach me.


I'll be at my uncle's house if you need to reach me.


I'll be at my uncle's house should you need to reach me.


If something unpredictable happens, which causes you to need to reach me, you will be able to reach me at my uncle's house.


There is a chance that something will happen which will cause you to need to reach me. We can't anticipate exactly what that event will be, or even if it will happen. It is unlikely to happen, but if it does happen, it will just be one of those common things in life where a situation goes slightly wrong in an unexpected way. I will be at my uncle's house. So, if one of those vicissitudes happens, please call or visit me at my uncle's house, and the situation will turn out OK.



The central meanings of would and should


The central meaning of shall and should is to indicate the normal, proper, expected, desirable, good way that something happens—as opposed to will and would, which mean what actually “will” happen or might have happened. For example, “You should pay your bills promptly” is good advice. “You will pay your bills promptly” is a prediction about the future.


A central meaning shared by should and would is to indicate the consequence of a hypothetical condition, as opposed to shall and will, which primarily indicate propriety and the future tense (and volition). For example, “If you had invested in Apple 15 years ago, you would be wealthy today.”


In combination with its central meaning of normal, proper behavior or outcome, the conditional mood gives should an extra connotation of uncertainty. For example, “If you invest your money wisely, you should become wealthy.” That means the same as “If you invest your money wisely, and nothing strange and unfortunate happens, such as an economic collapse or you have a terrible accident or your bank gets robbed or who-knows-what, then you will become wealthy.” When you say should, this implies that something might go wrong, since unforeseen or undesirable events sometimes interfere with the normal flow of events.



Softening via the conditional mood


English, like many languages, uses the conditional mood to “soften” a statement. For example, people often say “I would like some coffee” to request coffee politely, because that’s softer than “I will have some coffee.” What makes it soft is that you’re using the conditional mood even though there’s no condition. You’re using the word that means a consequence of a condition, but there’s no condition.


This is what’s happening in your example. Notice that should is optional in your example. It just softens the idea that you might need to reach me. It suggests that you probably won’t need to reach me, or that you need not worry about it because even if it does happen, we have the situation well in hand.


You might wonder, if should’s central meaning is to indicate the normal, proper outcome, why, in the example, does it describe an unforeseeable situation where something goes wrong, perhaps an emergency? A full answer would take a long time to explain (see below), but here’s a useful short answer: this is one way the word should gets “stretched” to fulfill a wide variety of needs.


How to learn this


I recommend that you not try to memorize rules for when to use should, when to use would, etc. You should understand the main ideas and then just learn idioms through experience.


The main ideas are: (1) a central meaning of shall and should, not shared by will and would, is to indicate normal, proper action or outcome; (2) both should and would have a central meaning of indicating a consequence of a hypothetical condition; (3) these words get “stretched” into a wide variety of meanings—far beyond their central meanings.


The idioms are chaotic and highly varied. For example, you can use should as a synonym for if, especially when describing something going wrong. For example, “Should you miss your train, you can use my phone to call a cab.” Scientists study all these idioms and try to figure out exactly what all the rules are; and some scientists say that idioms don’t really follow rules. If you’re just learning how to communicate in English, you’re better off picking up the idioms through experience, slowly and patiently, than trying to memorize a definitive list of rules.




I haven’t told you the full extent of the messiness.



English often uses the past tense to express a hypothetical future situation (“If you left within the next hour, you should arrive by noon.”). Would is the past tense of will, and should is the past tense of shall even though shall is now rare and never put into the past tense! This is enough to make should suitable for some hypothetical future situations, though (introducing the condition rather than the consequence). For example, “If you should arrive late, the meeting will be canceled.”


I wrote a long explanation here. It's probably too long, but it explains some of the history of these words, how they overlap with each other, and how conflicts between them usually get resolved.


phrase meaning - Help understanding 'God loves everyone equally, 100 percent.'


I am trying to understand the article shown in the quote below:



One is that God's love is like the sun -- he loves everyone equally and that means 100 percent. He loves bad people just as much as he loves good people. He loves Muslims, Catholics, homosexuals, politicians, millionaires, liars, dishonest people, murderers, school teachers, soldiers, Iraqis, Israelis, the mentally ill, Mother Teresa and Saddam Hussein equally, and his love is infinite. Just as the sun shines on everyone equally and the rain falls on everyone equally, so also God loves everyone equally, 100 percent.




How should I interpret the sentence "God loves everyone equally, 100 percent." (Marked as bold in the quote)? Does this mean "100 percent of God loves each and every one", or does this rather mean "God loves 100 percent of each and every person"?



Answer



This means that God loves every single person the exact same amount (that is, if love can even be quantified, and for this article, let's assume it can be). 100% of the love He gives to one person is the same amount of love He gives to anyone else. He won't love one person 100% and then love someone else 50% (which is to say, not as much).


Monday, April 18, 2016

word usage - How can I say "it was tried"?


In my thesis I want to write the following:



Second, by using the [...] and [...] it was tried to find an appropriate model.



I am not sure about the "it was tried". Can I use it? What would be better?



Answer



I don't think "it was tried" followed by an infinitive is acceptable English. If you have to use the passive voice for stylistic reasons, you could instead say "an attempt was made":




Second, by using the [...] and [...], an attempt was made to find an appropriate model.



mesh - Using instancing for everything?



Instancing improves performance (significantly) when rendering multiple (hunders? thousands?) copies of the same mesh at once. But how much overhead does it have when rendering exactly one copy with one draw call? Would it be a good or a bad idea to use instancing for all geometry rendered by engine?


Edit: Let's say we're creating an FPS game. Most of the objects have only one instance: a knife, a gun, a machine gun, a building and a radio tower. But there are also some objects with multiple instances: trees (e.g. 3 kinds of trees with hundreds of instances), grass and so on... What I mean is: instead of rendering the one-instance objects the "traditional" way and trees and grass using instancing, we render all of them using instancing. So our radio tower has only one instance (whose information we store in an instance data buffer) and we render that tower using some kind of DrawInstanced() call with instance count equal 1. Same with all other objects (of course, trees and grass have multiple instances).


So my question is: is it a bad idea to draw a single instance of an object using instancing? Does instancing have too much of an overhead (memory- and performance-wise) or is it in any way undesired for rendering single-instance objects?




unity - How to design context menus based on whatever the object is?


I'm looking for a solution for a "Right Click Options" behaviour.


Basically any and every item in a game, when right clicked, can display a set of options based on whatever the object is.


Right click examples for different scenarios:


Inventory: Helmet shows options (Equip, Use, Drop, Description)


Bank: Helmet shows options (Take 1, Take X, Take All, Description)


Floor: Helmet shows options (Take, Walk Here, Description)


Obviously each option somehow points to a certain method that does what is says. This is part of the issue I'm trying to figure out. With so many potention options for a single item, how would I have my classes designed in such a way as to not be extremely messy?



  • I've thought about inheritance but that could be really long winded and the chain could be huge.


  • I've thought about using interfaces, but this would probably restrict me a little as I wouldn't be able to load item data from an Xml file and place it into a generic "Item" class.


I'm basing my desired end result on a game called Runescape. Every object can be right clicked in the game and depending on what it is, and where it is (inventory, floor, bank etc.) displays a different set of options available to the player to interact with.


How would I go about achieving this? What approach should I take to first of all, decide which options SHOULD be displayed and once clicked, how to call the corresponding method.


I am using C# and Unity3D, but any examples provided do not have to be related to either of them as I'm after a pattern as opposed to actual code.


Any help is much appreciated and if I have not been clear in my question or desired results, please post a comment and I'll tend to it ASAP.


Here is what I have tried so far:



  • I've actually managed to implement a generic "Item" class that holds all of the values for different types of items (extra attack, extra defence, cost etc...). These variables get populated by data from an Xml file.

  • I have thought about placing every single possible interaction method inside of the Item class but I think this is unbelievably messy and poor form. I've probably taken the wrong approach for implementing this kind of system by only using the one class and not sub-classing to different items, but its the only way I can load the data from an Xml and store it in the class.


  • The reason I've chose to load all my items from an Xml file is due to this game having the possibility for 40,000+ items. If my math is correct, a class for each item is a lot of classes.



Answer



As with everything in software development, there is no ideal solution. Only the solution which is ideal for you and your project. Here are some you could use.


Option 1: The procedural model


The ancient obsolete old-school method.


All items are dumb plain-old-data types without any methods but lots of public attributes which represent all properties an item could have, including some boolean flags like isEdible, isEquipable etc. which determine what context menu entries are available for it (maybe you could also do without these flags when you can derive it from the values of other attributes). Have some methods like Eat, Equip etc. in your player class which takes an item and which has all the logic to process it according to the attribute values.



This is more of a OOP-by-the-book solution which is based on inheritance and polymorphism.


Have a base-class Item from which other items like EdibleItem, EquipableItem etc. inherit. The base class should have a public method GetContextMenuEntriesForBank, GetContextMenuEntriesForFloor etc. which return a list of ContextMenuEntry. Each inheriting class would override these methods to return the context menu entries which are appropriate for this item type. It could also call the same method of the base class to get some default entries which are applicable for any item type. The ContextMenuEntry would be a class with a method Perform which then calls the relevant method from the Item which created it (you could use a delegate for this).



Regarding your problems with implementing this pattern when reading data from the XML file: First examine the XML node for each item to determine the type of item, then use specialized code for each type to create an instance of the appropriate sub-class.



This pattern uses composition instead of inheritance and is closer to how the rest of Unity works. Depending on how you structure your game it might be possible/beneficial to use the Unity component system for this... or not, your mileage may vary.


Each object of class Item would have a list of components like Equipable, Edible, Sellable, Drinkable, etc. An item can have one or none of each component (for example, a helmet made of chocolate would be both Equipable and Edible, and when it is not a plot-critical quest item also Sellable). The programming logic which is specific to the component is implemented in that component. When the user right-clicks on an item, the components of the item are iterated and context-menu entries are added for each component which exists. When the user selects one of these entries, the component which added that entry processes the option.


You could represent this in your XML-file by having a sub-node for each component. Example:



   
Chocolate Helmet
helmet-chocolate.png
Protects you from enemies and from starving


sweet
2560


head
20


120



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