Friday, November 30, 2018

c++ - How do I start writing an MMO game server?



I am developing a multi-player on-line game.


I just started coding the server but I have no idea how to do it. Do I have to use threads ?


And if i do, do I need one thread for every client?


Knowing that I am using UDP, can I use multiple sockets in different threads to send packets on the same port?


edit:


server does:


-listen for client connections

-when a client connects:

-update files (send new files to the client)

-retrieve data from database

-loop to retrieve and update live data


-when client disconnects:

-update data in database

Answer



I may be wrong, but your question makes it seem like you are missing a lot of knowledge in order to successfully write an MMO server. I know this message will likely fall on deaf ears because I was in your position when I started programming.


My answer: If I were you I would start smaller. If you want to learn to write an MMO server I would do the following.



  • Write a TCP based p2p chat client.

  • Extend that chat client to work with NAT routers


  • Extend the chat client to have a central server that authenticates and stores message history

  • Extend it to have a secure handshake with the server to verify the client software and server software/location

  • Write a high level architecture of what you would want your MMO server to be

  • Read some articles on MMO server architectures

  • Start expanding your high level architecture into more and more detail

  • Write essential user stories for your architecture

  • start implementing your server


The answer you probably want:




  • Write a thread for the listener to accept incoming connections using TCP

  • Once the player is connected, use TCP for chat messages and sector changes

  • Use UDP for in-sector movement

  • Each connection gets its own thread for the messaging

  • UDP can be implemented with threads (if you really want) but I would probably use some sort of queue on one thread that accepts movement messages. Or spread it out depending on how many connections you get.


grammar - Difference between "Past Tense " and "Present Tense"


He began to move to leave the bus.


He begins moving to leave the bus.


I am on the bus now I try to make a sentence to describe someone want to leave the bus.


SO, Should I use present or past? Infinitive or Gerund? Please help.




vocabulary - nation or country


Across the world, in fact, nations don't spur growth so much as dynamic regions-- modern versions of the original megalopolis a term coined by Gottman to identify the sprawling Boston-New York-Washington economic power corridor.


I am wondering if we could substitute nation for country




c# - Clipping polygons in XNA with stencil (not using spritebatch)


The problem... i'm drawing polygons, in this case boxes, and i want clip children polygons with its parent's client area.


enter image description here


    // Class Region
public void Render(GraphicsDevice Device, Camera Camera)
{
int StencilLevel = 0;
Device.Clear( ClearOptions.Stencil, Vector4.Zero, 0, StencilLevel );
Render( Device, Camera, StencilLevel );
}


private void Render(GraphicsDevice Device, Camera Camera, int StencilLevel)
{
Device.SamplerStates[0] = this.SamplerState;
Device.Textures[0] = this.Texture;
Device.RasterizerState = RasterizerState.CullNone;
Device.BlendState = BlendState.AlphaBlend;
Device.DepthStencilState = DepthStencilState.Default;

Effect.Prepare(this, Camera );


Device.DepthStencilState = GlobalContext.GraphicsStates.IncMask;
Device.ReferenceStencil = StencilLevel;

foreach ( EffectPass pass in Effect.Techniques[Technique].Passes )
{
pass.Apply( );
Device.DrawUserIndexedPrimitives( PrimitiveType.TriangleList, VertexData, 0, VertexData.Length, IndexData, 0, PrimitiveCount );
}


foreach ( Region child in ChildrenRegions )
{
child.Render( Device, Camera, StencilLevel + 1 );
}

Effect.Prepare( this, Camera );

// This does not works
Device.BlendState = GlobalContext.GraphicsStates.NoWriteColor;
Device.DepthStencilState = GlobalContext.GraphicsStates.DecMask;

Device.ReferenceStencil = StencilLevel; // This should be +1, but in that case the last drrawed is blue and overlap all

foreach ( EffectPass pass in Effect.Techniques[Technique].Passes )
{
pass.Apply( );
Device.DrawUserIndexedPrimitives( PrimitiveType.TriangleList, VertexData, 0, VertexData.Length, IndexData, 0, PrimitiveCount );
}
}




public static class GraphicsStates
{
public static BlendState NoWriteColor = new BlendState( )
{
ColorSourceBlend = Blend.One,
AlphaSourceBlend = Blend.One,
ColorDestinationBlend = Blend.InverseSourceAlpha,
AlphaDestinationBlend = Blend.InverseSourceAlpha,
ColorWriteChannels1 = ColorWriteChannels.None

};

public static DepthStencilState IncMask = new DepthStencilState( )
{
StencilEnable = true,
StencilFunction = CompareFunction.Equal,
StencilPass = StencilOperation.IncrementSaturation,
};

public static DepthStencilState DecMask = new DepthStencilState( )

{
StencilEnable = true,
StencilFunction = CompareFunction.Equal,
StencilPass = StencilOperation.DecrementSaturation,
};
}

How can achieve this?


EDIT: I've just relized that the NoWriteColors.ColorWriteChannels1 should be NoWriteColors.ColorWriteChannels. :)


Now it's clipping right.



Any other approach?




Thursday, November 29, 2018

prepositions - Why do we have to use 'to' instead of 'will'?


I saw the sentence like




Donald Trump to run for president next month.



in the newspaper on the internet.


But I don't know why we have to use to instead of will.


Is there any rule I don't know?


Can anyone tell me the reason why we should use to in the news?



Answer



With the future, the infinitive form expresses intention whereas will + can express either an intention or the inevitable.


Consider this scenario:


Thousands of scientists worldwide agree that the polar ice cap will melt, based on their careful observations, unless measures are taken to dramatically reduce emissions of so-called greenhouse gases.



How might the headline read?


POLAR ICE-CAP TO MELT


POLAR ICE-CAP WILL MELT


Does the polar-ice cap intend to melt? No. So the verb would be will.


But let's say a government plans to cut the budget of its environmental watchdog agency. That is their intention.


GOVT TO CUT BUDGET OF ENVIRONMENTAL AGENCY


GOVT WILL CUT BUDGET OF ENVIRONMENTAL AGENCY


There, the choice is less clear. Probably the infinitive, but not necessarily.


Wednesday, November 28, 2018

meaning - "Will + be + verb -ing)" vs "Will + verb" ?


Can someone explain me the constructions (or however they are called) with the "Will + be + verb -ing)" and the "Will + verb" ?



Answer




Will + be + verb-ing


This is the future continuous/progressive tense. It describes an action that will be on going or in progress sometime in the future. It is often combined with a time reference. For example:



"Can you go shopping with me this afternoon?" asks one.


"I will be visiting my neighbor this afternoon," responds another.



The response indicates that a visit will be in progress "this afternoon."


The future continuous tense can be used without the time reference, but that presumes a time reference was provided or implied earlier in the discussion or narrative (or the statement doens't make sense).



"What will you be doing at seven o'clock?" asks one.



"I will be visiting my neighbor," responds another.



Will + verb


This is the future tense or simple future tense. It only indicates that something will happen in the future, but tells us nothing about the nature of that event. It is often used with a condition, meaning something must be completed first before moving on to the future task. For example:



I will visit my neighbor when I'm done sewing.



The future task is "visit my neighbor." The condition that must be completed before that task is "sewing."


The future tense can be used without a condition. For example:




"Who will clean up this mess?" asks one.


"I will do it," responds another.



Tuesday, November 27, 2018

unity - "The Object you want to Instantiate is null" But it works, can I ignore the error?


This has never happened to me so I'm a bit confused.


GameObject someObject = Instantiate (Resources.Load ("Prefabs/Items/" + someName)) as GameObject;

This throws an error but the object is actually instantiated and everything works as intended. The error doesn't stop the program no matter how many times I reproduce this.


Can I ignore this error or is there some problem that I'm not seeing?




Monday, November 26, 2018

idioms - Why is 'what will you do tomorrow evening' incorrect?



‘What will you do / are you doing tomorrow evening?’ ‘Nothing. I’m free.’
(Essential Grammar in Use)




The book says ‘are you doing’ is correct. But I don’t know why ‘will you do’ is not correct?



Answer



As snailboat pointed out in a comment on your question, the premise of this question is mistaken. "What will you do tomorrow?" is grammatical, acceptable and idiomatic in certain circumstances. For example:



Anna: Oh no! My running shoes are ruined! Now I won't be able to go for my usual evening run tomorrow.


Joel: Oh dear! What will you do tomorrow evening instead?



The difference between "What will you do tomorrow?" and "What are you doing tomorrow?" is not a question of grammaticality - both are grammatical - or even one of how idiomatic the sentence appears. The difference is what the question is asking:


"What are you doing tomorrow?" is a question that asks the listener what plans they have already made for tomorrow. It is passive, and is merely asking for information from the listener.



"What will you do tomorrow?" is a question that asks the listener to make a decision about what to do tomorrow. This question is more active. It asks the listener to create a plan and then tell the questioner what the newly formulated plan is.


Consequently, after some event that forces the listener to change their plans for tomorrow, "What will you do tomorrow [now that your previous plan is no longer valid]?" is more idiomatic than "What are you doing tomorrow [now that your previous plan is no longer valid]?", because there has not been time to produce a new plan, and the listener must therefore create a new one, rather than merely recite the plan that they had already made.


In contrast, if the listener has indicated that they are busy tomorrow, "What are you doing tomorrow?" is more appropriate, since the implication is that the listener has already made plans, and the questioner is inquiring what those plans might be.


There is also a small difference in subtext to the two questions as well. "What are you doing tomorrow?" is more passive, but also includes a possible subtext of asking whether the questioner can join in the activity. "What will you do tomorrow?" on the other hand contains a possible subtext of asking what the listener will do without the speaker, and can thus be construed as more cold.


unity - Can I use a 3d plane for a 2d game?


I am developing a 2d isometric game and I was wondering if I can use a 3d plane for a 2d game.



Answer



Sure, you want an orthographic projection.


Aside from that, you can render using an isometric point of view. That will allow you to look at surface with square tiles and have them appear as isometric tiles. Also, should allow you to use 3D models in your isometric game without worrying about the projection.


The following is from the Wikipedia link above:



There are eight different orientations to obtain an isometric view, depending into which octant the viewer looks. The isometric transform from a point ax,y,z in 3D space to a point bx,y in 2D space looking into the first octant can be written mathematically with rotation matrices as:


Isometrix matrix


where α = arcsin(tan 30°) ≈ 35.264° and β = 45°. As explained above, this is a rotation around the vertical (here y) axis by β, followed by a rotation around the horizontal (here x) axis by α.



(...)


The other 7 possibilities are obtained by either rotating to the opposite sides or not, and then inverting the view direction or not.



Emphasis mine.


Notice the article says there 8 possible such matrices. Some testing will be required to make sure you are use the right one for the coordinates of your map.




For unity, you want to set an orthographic matrix in Camera.projectionMatrix and the isometric matrix shown above in Camera.worldToCameraMatrix.


Note: I don't really have experience with Unity. So I can't tell if Camera.orthographic is a better option than setting an orthograpic matrix to Camera.projectionMatrix.


If you need to set the camera by hand, use the angles shown above (α = arcsin(tan 30°) ≈ 35.264° and β = 45°):


Demostration of angles to set isometric view



xna - Obtaining a world point from a screen point with an orthographic projection


I assumed this was a straightforward problem but it has been plaguing me for days.


I am creating a 2D game with an orthographic camera. I am using a 3D camera rather than just hacking it because I want to support rotating, panning, and zooming. Unfortunately the math overwhelms me when I'm trying to figure out how to determine if a clicked point intersects a bounds (let's say rectangular) in the game.


I was under the impression that I could simply transform the screen point (the clicked point) by the inverse of the camera's View * Projection matrix to obtain the world coordinates of the clicked point. Unfortunately this is not the case at all; I get some point that seems to be in some completely different coordinate system.


So then as a sanity check I tried taking an arbitrary world point and transforming it by the camera's View*Projection matrices. Surely this should get me the corresponding screen point, but even that didn't work, and it is quickly shattering any illusion I had that I understood 3D coordinate systems and the math involved.


So, if I could form this into a question: How would I use my camera's state information (view and projection matrices, for instance) to transform a world point to a screen point, and vice versa? I hope the problem will be simpler since I'm using an orthographic camera and can make several assumptions from that.


I very much appreciate any help. If it makes a difference, I'm using XNA Game Studio.




Sunday, November 25, 2018

word difference - How should "come" and "go" be used in the following context?



I just had an argument with my mom about the usage of "come" and "go". Last night, my aunt was at my house, and my mom and I were in the car, on the way home. I called my aunt and said "I'm coming home." After I hung up, my mom told me that I should have said "I'm going home."


If the person I am speaking to is not at my house, of course I would tell them that "I'm going home." But what if they're at my house? Does the usage of "come" and "go" depend on where the listener is, or just the speaker?



Answer



It is very simple. If the listener is at your home, and you're going home, then you should say :



I'm coming home.



If the listener is elsewhere, you should say :



I'm going home.




Note that in the beginning of this answer, I've said "..and you're going home..". This is because I'm not at your home. It is as simple as that.

Note:
Say you're in the Army and you're posted somewhere far from home. Now, you're speaking to your friend who stays in your hometown. You can tell him "I'm coming home.". This doesn't mean he's at your home. But here, when the speaker refers to "his home", he is talking about his home, as well as his hometown. Generally, if the listener is in the area of reference, you could use "come".


Saturday, November 24, 2018

tools - 'Binary XML' for game data?


I'm working on a level editing tool that saves its data as XML.


This is ideal during development, as it's painless to make small changes to the data format, and it works nicely with tree-like data.


The downside, though, is that the XML files are rather bloated, mostly due to duplication of tag and attribute names. Also due to numeric data taking significantly more space than using native datatypes. A small level could easily end up as 1Mb+. I want to get these sizes down significantly, especially if the system is to be used for a game on the iPhone or other devices with relatively limited memory.


The optimal solution, for memory and performance, would be to convert the XML to a binary level format. But I don't want to do this. I want to keep the format fairly flexible. XML makes it very easy to add new attributes to objects, and give them a default value if an old version of the data is loaded. So I want to keep with the hierarchy of nodes, with attributes as name-value pairs.


But I need to store this in a more compact format - to remove the massive duplication of tag/attribute names. Maybe also to give attributes native types, so, for example floating-point data is stored as 4 bytes per float, not as a text string.


Google/Wikipedia reveal that 'binary XML' is hardly a new problem - it's been solved a number of times already. Has anyone here got experience with any of the existing systems/standards? - are any ideal for games use - with a free, lightweight and cross-platform parser/loader library (C/C++) available?



Or should I reinvent this wheel myself?


Or am I better off forgetting the ideal, and just compressing my raw .xml data (it should pack well with zip-like compression), and just taking the memory/performance hit on-load?



Answer



We used binary XML heavily for Superman Returns: The Videogame. We're talking thousands and thousands of files. It worked OK, but honestly didn't seem worth the effort. It ate up a noticeable fraction of our loading time, and the "flexibility" of XML didn't scale up. After a while, our data files had too many weird identifiers, external references that needed to be kept in sync, and other strange requirements for them to really be feasibly human-edited any more.


Also, XML is really a markup format, and not a data format. It's optimized for a lot of text with occasional tags. It isn't great for fully structured data. It wasn't my call, but if it had been and I knew then what I know now, I probably would have done JSON or YAML. They're both terse enough to not require compaction, and are optimized for representing data, not text.


past tense - It's been a long time since I (went/have been) to Canada



It's been a long time since I went to Canada




Does the above sentence mean: since first or last went to Canada?


When you as a native speaker hear the above and below sentences, could you give me probabilities (by a sample of number of visits ) on the difference between those two sentences? This is of course if the first sentence has the meaning: first went to Canada



It's been a long time since I have been to Canada



If you feel it is better to change a long time into e.g. 5 years to make your answer clearer, then please do so.



Answer




It's been a long time since I went to Canada.




To me, the above sentence is ideal only in cases where there is only one visit to Canada. In that sense, it would be both a first and the last (most recent) visit. That said, it's a valid construction in a situation where multiple visits had occurred, but in these cases I’d argue for:



It's been a long time since I have been to Canada.



The way I figure it, the statement above has two main pieces of information:




  1. I have been to Canada (at least once; possibly multiple times)





  2. It has been a long time since then (since my last visit)




Broken down the same way, the first sentence has these two main pieces of information:



  1. I went to Canada (most likely just once)

  2. It's been a long time since then (since my one and only visit)


So it comes down to what you want to say. This might be the situation:




  1. I went to Canada throughout my teens

  2. It's been a long time since then


You could make an argument for either option in this case, but I maintain that the second sentence would more clearly indicate multiple visits.


publishing - Publish Python Game



I wrote a Python game in for a group project using Pygame. Now we wanted to package it into an executable but I can't seem to do it. When I was working with C# through Microsoft Visual Studio it had a really simple publish feature. Is there an editor that can do that for Python with external libraries?




Answer



I've had luck compiling to executable using PyInstaller. Another possibility, as Luiz mentions, is py2exe.


Both of these tools have options to bundle all of the python libraries into the executable if you want, making it easy to distribute. Either of these might have issues with whatever libraries you might be using, so it might be easiest to check the forum of the libraries you're using to see if they have a recommendation.


How to smoothly move camera when the player is climbing a diagonal staircase in 2D tile-based side-scroller?


I am working on a game, which is tile-based, similar to the way Terraria works. My player is 2 x 3 and can move over one-high obstacles, but this creates a very jittery effect, since my camera currently strictly follows the player. I was thinking of either somehow implementing a smoother camera movement or overhauling the player movement itself. I would love some feedback on how one might go about fixing this.



Answer




In the scenario you describe, there are two points that could improve the smoothness of your camera: (1) the position of the camera with respect to the player, and (2) the movement of the camera towards its target position.



You mention your camera is locked to the player. I assume you instantly snap your camera's center of focus to the player position. It is possible to handle this differently by having a small frame around the player, where the camera does not follow the player. As soon as the player moves beyond the frame, the camera is "pushed" back towards the player.


In your case, you mention the jitter being caused by "jumps" in the vertical player position when he climbs a one-tile ledge. You can apply the framing strategy above to the X- and Y-movement of the camera independently. If you do want to keep the player centered on screen horizontally, but want to avoid jitter due to sudden vertical movement, you can apply the strategy to the Y-axis only.


Your current camera strategy might look like this in pseudo-code:


// Update the player position
...

// Update the camera position
camera.x = player.x;

camera.y = player.y;

To apply framing, you could modify your code like this:


// Update the player position
...

// Update the camera position
const float camera_frame_size_hor = 48.f;
const float camera_frame_size_ver = 32.f;
camera.x = min(max(camera.x, player.x - camera_frame_size_hor), player.x + camera_frame_size_hor);

camera.y = min(max(camera.y, player.y - camera_frame_size_ver), player.y + camera_frame_size_ver);

In the above cas,e the camera will only follow the player when he moves more than 48 pixels away from the camera center horizontally, or more than 32 pixels away from the camera center vertically.



You also mention you instantly snap the camera to the player position. Many games apply a form of smoothing to the camera movement. To apply smoothing, you calculate the target camera position as before. However instead of simple setting the camera's actual position to this target position, you gradually move its position towards the target.


Currently, you might simply set your camera position directly as follows:


// Update the player position
...

// Update the camera position

camera.x = player.x;
camera.y = player.y;

You could instead apply a simple low-pass filter as follows:


// Update the player position
...

// Update the camera position
const int camera_smoothing = 10;
float camera_target_x = player.x;

float camera_target_y = player.y;
camera.x = ((camera.x) * (camera_smoothing - 1) + camera_target_x) / camera_smoothing;
camera.y = ((camera.y) * (camera_smoothing - 1) + camera_target_y) / camera_smoothing;


The two techniques above can be applied independently to smooth your camera movement in a more sophisticated way. Your camera code might look like this:


// Update the player position
...

// Update the camera position

const int camera_smoothing = 10;
const float camera_frame_size_hor = 48.f;
const float camera_frame_size_ver = 32.f;

float camera_target_x = min(max(camera.x, player.x - camera_frame_size_hor), player.x + camera_frame_size_hor);
float camera_target_y = min(max(camera.y, player.y - camera_frame_size_ver), player.y + camera_frame_size_ver);
camera.x = ((camera.x) * (camera_smoothing - 1) + camera_target_x) / camera_smoothing;
camera.y = ((camera.y) * (camera_smoothing - 1) + camera_target_y) / camera_smoothing;



I would like to recommend the following excellent article which analyses various camera strategies across many games. The articles has animated graphics to illustrate all strategies. Itay Keren - Scroll Back: The Theory and Practice of Cameras in Side-Scrollers


Friday, November 23, 2018

Question sentences involving negation



(1) Does he not know?



(2) Doesn't he know?



I don't usually see and hear questions formed in the first style. I was even surprised to know that it is grammatically correct. And actually it is the most "proper" way to form an interrogative sentence. Ngram shows that the first style was much more popular before than now.


What are your suggestions on choosing between these styles? And I will probably add the third one.



(3) He does not know?



EDIT:


The answers have explained how to form a question, but have not actually provided an account on the usage of the first two forms. Especially I'm interested in the first form: does it sound formal, is it used in speech or only in writing, et cetera.




javascript - Cocos2d JS - Getting vector reflection



I'm working on a small Breakout clone using Cocos2D-JS, without the use of a physics engine.


One of the things that baffles me was how the ball bounces. My friend came up with this:



inputVector - 2(normalVector * inputVector)



I have no idea how to translate that in code. So I tried with this:


g_Ball.position = this.velocityComputer(cc.p(g_Ball.x, g_Ball.y), cc.p(this.x, this.y));

velocityComputer: function(inVector, thisNVector) {
var prodVec = cc.pDot(inVector, thisNVector);

var retVec = inVector - (2 * (prodVec * inVector));
cc.log(retVec);
// cc.log(blockNVec);
return retVec;
},

But g_Ball doesn't change directions, and retVec simply logs NaN.


Any suggestions?


Thanks.




grammar - uses of with, at, of


I would like to now if I am using the prepositions correctly:


"She was not pleased with her job and was tired of doing the same thing every day, but everybody was surprised at her attitude"


I always confuse them.




meaning - won't instead of using' wouldn't' is possible?



I have asked many questions about "would" both in ELL and ELU. But I still have a question about the use of "would". I have recently asked a question which @Jay also answered. He used "wouldn't" in the following sentences: 1. Here, you wouldn't say, "May I ask you what is your name?" Though we break this rule for questions sometimes 2. Well, someone might say that in informal speech, but you wouldn't write it or use it in formal speech. 3. "May I ask you what's your name?" is awkward; a fluent speaker wouldn't say that.


I had asked Use and meaning of "wouldn't" in "you wouldn't" and "a speaker wouldn't" question in ELL and I have received answers for it. But there is one thing that I'm still confused about.


Do the meanings of the sentences above change if we use 'won't' instead of using 'wouldn't' ? can we use 'won't' in the place of 'wouldn't' without changing the meanings of the sentences above?



Answer



Wouldn't and won't are not interchangeable in your three sentences. The meanings of the sentences are different depending upon which form of the verb is used.


If wouldn't is replaced by won't in the first sentence, we have:




  1. Here, you won't say, "May I ask you what is your name?"




Won't (a contraction of will not, the present tense of the verb will with the negative adverb) describes the future from the viewpoint of that future; it describes the future as "its own present." Wouldn't (a contraction of would not, the past tense of the verb will with the negative adverb) describes the future as if viewed from a time further ahead of the present than that future; it describes the future as "its own past."


It is always important to remember that even when the verb will is used as a modal or auxiliary verb, it is not merely a neutral word which places the action in the future. Every use of the verb will also partakes of its original meaning of wish for or want. Thus, wouldn't in your first sentence gives it the meaning:



Looking back at your words as if you had already spoken them, you wish you had not said "May I ask you what is your name?"



This expresses a strong preference for not using those words.


Replacing wouldn't with won't gives the sentence this meaning:



Looking at your words as if you are in the future and speaking them, you do not say "May I ask you what is your name?"




This merely states that, in the future, you do not use those words, with no sense of preference.


The meaning of will as to desire, wish is strong when the past tense would is used, and especially when in the negative as in your sentences. The construction You wouldn't +[bare infinitive] or You wouldn't want +[infinitive] is often used in English to suggest, emphatically, a negative desire or preference:



You wouldn't eat dirt!
You wouldn't want to get a speeding ticket!
‘But you wouldn’t want to read a whole book of text speak,’ I said. (Source)



Thursday, November 22, 2018

Different ways to store a 2D map/landscape in XNA


I was looking around at this site about eight months ago and wish I saved the location of this topic but I was wondering the different map rendering styles that you can do in XNA. The one style I looked at was using a text file to pull characters like "X" would be a monster and "O" would be the player. Is there another way with out an external file that I can put tiles from a sprite sheet to randomly create a map. Of course when dealing with random buildings I would have certain building designs so that if some one was playing they wouldn't see a building with half a wall missing.


This is for a top down 2D game.




headlinese - Meaning of "somebody/something to verb"


I saw an article starts with: "A company to launch a new product", in a news paper. I just wonder what does it mean? Is it a kind of usage of near future? (e.g. is to do something)




"I already was about to go to (no article /a /the) class tomorrow morning."


I was told that it is possible to say:




"I already was about to go to (no article) class tomorrow morning."



without an article after the the preposition "to" before the countable noun "class" in this example.


Well, the reason for that is not understood to me, while I obviously understand the difference between the articles "a"/"an" and "the" I don't understand the omitting of all articles here. If it's just non specific class we can say "I already was about to go to a class tomorrow", so why we omit the indefinite article here?



Answer



You go to school, university, classroom, office, and college etc for a purpose. And, this is a regular affair.


So, if the event is regular, and the purpose is clear (of studying), zero article.



Henry and Keith go to school




But when you emphasize the destination/place, you put an article.



I am going to the school to pick Henry and Keith.



Similarly,



I went to hotel soon after I landed there (for staying purpose)



but...




I went to the hotel to meet Mr Anderson (for specific meeting)



In above all examples, the place is specific and thus, the article the is put. But to answer your question, if there is a specific purpose for a specific place (like meeting someone), you may put the article or else, if it's a general event, you omit the article.


More on zero article is here.


style - How to avoid multiple "of-phrases" in one sentence?


I often find myself inclined to write something like the following:



Let's think about this problem from the point of view of readability and self-obvious design.



Two *of*s, which come one after another, look bad and sometimes disrupt the flow of thought. And it may be even worse — I start trying to introduce even more nested attributes, recursively.


I tried rewriting the top sentence using the readability and self-obvious design as an attribute of point of view, but that's even worse in my opinion.


How can I avoid such repetitive pattern and still be able to express complex attributes of subjects?




Answer



While what you have written here is perfectly acceptable, your points show a finely developed sense of style as well. In the case of your example, simply substituting "viewpoint of readability" should accomplish your goal.


To answer your broader question at the end, use your creativity, and find other ways to express multiple possessives. The above is an example.


c# - Class design and data structures for a Tower Defense


I was trying to come up with a structure for a simple TD game that has following elements





  1. Tower Each Tower has a set of properties like range, damage, health etc There could be different types of Towers with different attack types. For eg Tower A can perform attackType 1 and 2 and Tower B can perform attackType 3 and 4




  2. Creep Each Creep has a set of properties like damage, health, bountyPoints etc. There could be different types of Creeps with different abilities just like the Towers




For now I am trying to come with a good design that is scalable and well structured for the above two game elements


This is the skeleton of a Tower class that I have come up with so far. Please comment and suggest changes. Any design patterns that could make life easier



using System.Collections;
using System;

public enum TowerType
{
tA,
tB,
tC
};


public class Tower {

private TowerType type;
private int damage;
private int range;
private int health;

public Tower(TowerType type)
{
this.type = type;

initializeVariables();
}

private void initializeVariables()
{
if (this.type != null)
{
if (this.type == TowerType.tA)
{
this.damage = 20;

this.range = 40;
this.health = 50;
}

else if (this.type == TowerType.tB)
{
this.damage = 30;
this.range = 50;
this.health = 60;
}


else if (this.type == TowerType.tC)
{
this.damage = 60;
this.range = 60;
this.health = 80;
}

}
}


public int getDamage()
{
return this.damage;
}

public int getRange()
{
return this.range;
}


public int getHealth()
{
return this.health;
}

public TowerType getTowerType()
{
return this.type;
}


public string getType(int value)
{
return Enum.GetName(typeof(TowerType), value);
}
}

So using enums to define various types of towers. But is this a good design? Each Tower would have different damage, range and health.


What if there are 100 different towers? So in my InitializeVariables() would have a cluster of 100 if else statements. How can I improve on this or is there a better way to implement this?



Answer




Here is how i think it could be done


class Class1 {
public enum TowerType { A, B, C };
static private Dictionary towerTypesInfo;

static void init()
{
towerTypesInfo= new Dictionary(100);//100 tower types
towerTypesInfo.Add(TowerType.A, new Tower(20, 40, 50));
towerTypesInfo.Add(TowerType.B, new Tower(30, 50, 60));

//... fill in the rest 98 tower types with their values ...

//example of making a tower named tower1
Tower tower1 = new Tower(TowerType.A);
}

public class Tower {
public TowerType type { get; private set; }
public int damage { get; private set; }
public int range { get; private set; }

public int health { get; private set; }

public Tower(int d, int r, int h)
{
damage = d;
range = r;
health = h;
}
public Tower(TowerType type)
{

damage = towerTypesInfo[type].damage;
range = towerTypesInfo[type].range;
health = towerTypesInfo[type].health;
} } }

You don't need to make a function for every single variable you have, like in java. Just use public int damage { get; private set; }, C# has automated way of doing this with overwriting the default get; set; properties.


Also, You could fill this dictionary from a .txt if you wanted to. you could format the .txt to make it a bit easier to edit


TowerTypesInfo.txt:
A 20 40 50
B 30 50 60

C ...


mathematics - Kepler orbit : get position on the orbit over time


I'm developing a space-simulation related game, and I am having some trouble implementing the movement of binary stars, like this:


Binary star


The two stars orbit their centroid, and their trajectories are ellipses.



I basically know how to determine the angular velocity at any position, but not the angular velocity over time. So, for a given angle, I can very easily compute the stars position (cf. http://en.wikipedia.org/wiki/Orbit_equation).


I'd want to get the stars position over time. The parametric equations of the ellipse works but doesn't give the correct speed : { X(t) = a×cos(t) ; Y(t) = b×sin(t) }.


Is it possible, and how can it be done?



Answer



Following a few links from the Wikipedia page you reference leads to Position as a function of time.


Wednesday, November 21, 2018

british english - What is the right word to refer to a black person, when you don't know their name?


Excuse my ignorance, I have lived in the UK for 8 years however I still don't know how to refer to a black person, as I came from a country where racism was not an issue.


Some agency called me last week and I was trying to explain to the person over the phone that I had visited them a few days prior to his phone call and I had been served by one of his colleagues, he insisted on knowing the name of that person and I couldn't remember the name so I said it was the black guy. I could tell that it was not appropriate or maybe he just didn't like the way I described his colleague.


Should I have said "dark"? "tanned"? or what exactly? I can't think of saying black American (I hear that lots on TV) as I live in the UK and nobody is American. Also I don't know what to add to the word "Afro" to make the equivalent of "black".


I have asked a friend who isn't a native speaker either and she only confused me more by saying that I can't even call a blackboard that name any more but it has to called "whiteboard" in order not to offend black people.



Answer



In the UK, black person is the usual way to describe someone of African or Caribbean ethnic background and I wouldn't expect it to be taken as offensive. Referring to someone as a black (as a noun) would be offensive.


Referring to someone as the black guy could conceivably be interpreted as a little disrespectful if you might have been expected to call them by name, depending on the context. In your specific example you could have said I don't remember your colleague's name but he's black, if that helps? and I wouldn't expect anyone to be upset by that form of words.



Your friend is either misinformed or engaging in propaganda against perceived "political correctness". Stories about the word "black" being banned in some context or other pop up in the tabloid press with depressing regularity but invariably turn out to be untrue or misreported.


word usage - A comparison between "Creep", "Crawl" and "slither"


We have three too similar words: Creep, Crawl, Slither. These three words have very tiny and slight nuances. Based on dictionaries, one cannot recognize which ones can be used for the nouns: "snake" "snail" or or "lizard" or "soldier / child". I cannot recognize which verb can be used for which noun!


As far as I know, the creatures that have legs crawl and the animals that are legless can either slither or creep. So:


For instance:





  • A lizard / soldier / a child can only crawl on the ground.





  • A snake and a snail can only slither.





Does my understanding work in English logic? If not, please correct me and explain me how I am mistaken?



Answer



While there are some mechanical differences between the terms, the differences have mostly to do with feelings and connotations rather than physical differences. As such, depending on the context some of the words can be used interchangeably while others cannot.




slither - A snake-like way of sliding along the ground; think smooth and suspicious.




Although the word is derived from Middle English slidder which is derived from slide the act of "slithering" is more particular than simply "sliding". The word "slither" is almost exclusively used for snakes and when one wants to describe motion as snake-like. Because most native English speakers have negative cultural associations of snakes, words like "slither" therefore also inherit these bad associations.



creep - Implies slow movement, usually quiet or sneaky; but not necessarily negative.



If you look at the synonyms for the verb "creep" you'll notice words like tiptoe, sneak, and slink. All of these words describe motion with a deliberate, stealthy, quality. Although moving around stealthily might seem suspicious, there is generally less implied ill-intent when using the word "creep" compared to the word "slither".


Another definition of creep implies an exceptionally slow motion and is usually used to refer mostly to non-animal things. Mosses creep over rocks, vines creep up tree branches, time creeps by. In these cases there is no negative connotation implied.



crawl - Implies slow movement, usually low-to-the-ground and dragging the body along by pulling.



Crawling for humans and similar big animals involves having the body low to the ground (often times dragging or nearly dragging) and pulling oneself around. It is also often used (at least in North America) to generically describe the movement of most bugs/insects/snails/worms; in fact, I'd consider the use of "crawl" to be more natural than "slither" when describing the motion of a slug, snail, or worm. Crawling rarely implies any good or bad attitudes by itself.






When used in certain contexts some of these terms make sense when others do not. In some situations two words can be used interchangeably, other times they cannot. Here are a few example sentences that try to illustrate the differences.



The snake slithers through the grass to approach the mouse.


The snake creeps through the grass to approach the mouse.


The snake crawls through the grass to approach the mouse.



Slither is a word used to describe snake-like motion along the ground, so to say a snake slithers sounds absolutely natural. On the other hand, a snake doesn't have arms or legs to pull it's body along as it moves so crawl sounds very strange to a native speaker. The word creeps doesn't specifically imply sliding or arms so it could maybe be appropriate. Furthermore, creep implies the snake is being slow and/or sneaky as it approaches the mouse, which makes perfect sense if the snake is hunting the mouse.




The infant slithers over the rug to pet the soft kitty.


The infant creeps over the rug to pet the soft kitty.


The infant crawls over the rug to pet the soft kitty.



In this case, we know that babies crawl along on all fours hands and legs, and so the third sentence is correct. Babies don't make the smooth sliding snake-like motions that slithering might describe, so the first sentence is incorrect. Babies aren't naturally very sneaky, but a creative writer might imagine that a baby moves slowly (purposefully) to not scare away the kitty it wants to touch.


In this last set of sentences, all three of these sentences make sense, they just describe very different situations.



The man slithers up next to the young woman.



If a writer says that a man slithers up next to a young woman it is almost meant figuratively. In this context the writer implies that the man is moving suspiciously and probably with ill-intent; the reader would not be surprised if the writer called the man a pervert in the very next sentence.




The man creeps up next to the young woman.



If a writer says that a someone creeps up to someone it is almost always literal. We don't know if the man is good or bad, only that he approached stealthily enough to not be noticed. The writer has to provide additional context for the reader to know if the man is a kidnapper, or simply an old friend trying to surprise her.



The man crawls up next to the young woman.



If the man crawls up to the young woman the reader wonders "Why isn't he walking?". The wording implies that the man is moving by pulling himself along with his arms and legs which is highly unusual for most people's day-to-day encounters. This might make sense if they're both laying together on a beach, or if the man fell out of his wheelchair, etc.


grammaticality - must and should


"They told her over and over again that she must not do it." is a correct sentence. Is "should" OK instead of using "must" in this sentence? If so, "They told her over and over again that she not do it." might be OK, too?





procedural generation - How to generate a city street network?


I would like to create a city generator for a game, but I am facing a problem at the very start of the generation: the road system.


As it is a medieval world, I don't want a grid plan like many modern cities. I would ideally prefer a pseudo-random generation of large avenues and smaller streets, where it could be possible to get lost, but with still some logic - not a complete labyrinth.
Something that would look like a naturally grown town.


In order to keep it simple, let's say my cities would be on flat and stable terrains, without any river-crossing or relief problems. I could try to integrate it to a solution after.


I didn't decide of a precise size or disposition for my cities, so if you have a solution that would work only with cities of a precise form (square, circle, rectangle etc), I would take it.




Answer



A good place to start with procedural city generation is Parish and Müller's Procedural Modeling of Cities. Their paper presents an L-System in which rules concerning population density & road patterns (rectangular grid, radial & least elevation change) are combined and then fixed to accommodate local constraints such as water fronts & road aesthetics. While the results of this system are impressive, it has been criticized as being unnecessarily complicated. Barrett's alternative solution is restated in Rudzicz's Spare Parts dev blog as follows:



  • maintain a list of "proposed" roads

  • evaluate them in some order

  • if they are acceptable (with or without some minor modifications)

  • store each accepted road while "proposing" a handful more branching from it


This approach removes most of the symbol rewrite housekeeping inherit in Parish and Müller's L-System. You can see an demo of this approach here.


A benefit of this approach is that it is city shape agnostic - you can add outline constraints as needed, so your city shape can be determined by your game design needs rather than the algorithm. Depending on your city size, this might be good enough as is. Here's a result from the above demo with a segment limit of 100: enter image description here But if you need something big, you may have trouble; here's a result with a segment limit of 500: enter image description here



In part, you can adjust this by changing the road branching rules, avoiding 90 degree angles, etc. If your layout is still too regular, here's my correction:


Transform your city grid into a graph where each street is an edge & each intersection is a node. Next, use whatever algorithm you prefer to convert the graph into a maze. Here's the last example turned into a maze: enter image description here


Now the output has the opposite problem, it's too maze like. But now we can apply a couple of techniques from the Secret Workings of Jamis Buck's Dungeon Generator. First, increase the sparseness by removing some dead end corridors. Next, increase the connectivity by adding in roads that create loops (i.e. introduce cycles to the graph). Here's an example result: enter image description here


Note: it is possible to achieve the same final result directly from the earlier grid oriented layout stage (before generating the maze), by only apply edge removals to the city grid. The problem with that approach is you must ensure removing an edge doesn't partition the city thereby making portions unreachable.


Tuesday, November 20, 2018

Is it right conditional sentence?


description:




someone has a lyrics for the song and I discussed its plot and probable outcome



sentence (mixed):



It would be great song If it hadn't had such lyrics (but, in fact, it has)



explanation:


(second conditional + third conditional)




a condition clause (protasis) has an impact on the present state (it would be great NOW)


a consequence clause (apodosis) couldn't be undone and it was in the past




Answer



This conditional construction employs a ‘past perfect’ (had had) in the condition clause (protasis) as an irrealis to express the counterfactuality of that past eventuality, and a ‘past’ (would be) in the consequence clause (apodosis) to express the same counterfactuality in the present eventuality. This would be appropriate in this sort of situation:



He would be a rich man today if the song hadn’t had such an inadequate lyric.



That is, if the song had had a better lyric back then it would have sold much better over the years down to the present.


But in your example I don’t think it's the past inadequacy that makes the song less than great today: that’s caused by the fact that it still has those lyrics. Consequently I think what you want is an irrealis past in both clauses:




It would be a great song if it didn’t have such an inadequate lyric.



Incidentally, in actual grammatical studies we don't use the terms 'first, second, third conditional'—these are just teaching tools which don't represent any linguistic reality. You've clearly outgrown them, and you can discard them freely.


prepositional phrases - Where are the objects and the attributes in these sentences


Where are the objects and the attributes in these sentences?



There was no reply, but in a moment Miss Glaser began to play the opening bars of one of Schumann’s songs. It was no strain on the voice, and I guessed that Miss Glaser knew what she was doing when she chose it. La Falterona began to sing, in an undertone, but as she heard the sounds come from her lips and found that they were clear and pure she let herself go.



I'm particularly interested in "in a moment", "of one of Schumann’s songs", "from her lips" and "no strain on the voice".



The attribute is a secondary part of the sentence which characterizes person or non-person expressed by the headword either qualitatively, quantitatively, or from the point of view of situation. http://5fan.ru/wievjob.php?id=47143 and http://5fan.ru/wievjob.php?id=46987




3d - What exactly is UV and UVW Mapping?


Trying to understand some basic 3D concepts, at the moment I'm trying to figure out how textures actually work. I know that UV and UVW mapping are techniques that map 2D Textures to 3D Objects - Wikipedia told me as much. I googled for explanations but only found tutorials that assumed that I already know what it is.


From my understanding, each 3D Model is made out of Points, and several points create a face? Does each point or face have a secondary coordinate that maps to a x/y position in the 2D Texture? Or how does unwrapping manipulate the model?


Also, what does the W in UVW really do, what does it offer over UV? As I understand it, W maps to the Z coordinate, but in what situation would I have different textures for the same X/Y and different Z, wouldn't the Z part be invisible? Or am I completely misunderstanding this?



Answer



Your understanding is close. Each 3D model is made out of vertices. Each vertex usually defines the location of a point in space, a normal (used in lighting calculations) and 1 or more texture coordinates. These are generally designated as u for the horizontal part of the texture and v for the vertical.


When an object is textured, these coordinates are used to look up which texel or pixel to plot from the texture. I find it easiest to think of them as percentages or ratios between the left edge of texture (u = 0) and the right edge of the texture (u = 1.0) and from the top of the texture (v = 0) and the bottom of it (v = 1.0). They are interpolated between the vertices and looked up for each on-screen pixel that is rendered. They can be larger or smaller than these ranges and the render state that is set when the object is rendered specifies what happens. The options for this are CLAMP and REPEAT. Clamping limits the coordinate to either 0 or 1, causing the texture to smear where it is outside of the range. Repeat causes the texture to repeat when it is outside the range; it is effectively the same as grabbing just the decimal portion of the coordinate and using that in its place.


Before the texture coordinates are applied onto an object, they are multiplied by a texture matrix to apply some transformation to them (such as scaling, translation or rotation). This effect is sometimes animated in games to make it appear as though something is moving across an object without having to move the object itself... the texture is simply scrolling across it. When the texture matrix is multiplied by the texture coordinates, it produces 2 values that are used to look up the texel to plot (lets call them s and t). These are generated automatically from u and v even when the texture matrix is not set; it is the equivalent of multiplying u and v by an identity matrix.



This is where the w coordinate comes in, though it isn't used that often. It is an extra parameter to multiply the texture matrix against and is usually used when you want to take perspective into account (such as in Shadow Mapping). It works the same as when you transform a location in object-space to screen-space via a world-view-projection matrix. By multiplying the UVW with a projection transform, you end up with 2 coordinates, the s and t which are then mapped onto a 2D texture.


How do game bots perceive the game world & other entities?



This question has been on my mind for a while...mainly because I see bots for all sorts of games like WoW and others. My question is; how do the bots know what is appearing on the screen? I don't play WoW so my example may be wrong but if for example there is a monster, how does the bot know where that monster is on the screen and how does it know how to interact with it?


Can you apply this to any game or is it specific for each game? I'm sorry if the question isn't clear...and I'm not asking how to make a bot, more asking how they detect things on the screen as its quite fascinating to me!


Thanks in advance :)



Answer



There are many points where a bot can inject itself into the game.




  • The screen is one of them, but by far not the most useful. However, I have once seen a very early aimbot for Counter Strike which used color coding. It came with alternative character models with single-colored textures (the game was modding-friendly enough to allow this) and then just detected pixels of those colors. Not a very effective method, though. It was already quite clunky back then, and becomes less and less viable because graphic engines become more and more powerful, which means more and more detail to confuse any optical recognition algorithms.





  • Another point is reading the memory directly[1]. It is possible to have one program on your computer read the memory of another. So the developer just needs to find out at which memory address the game is saving the information which is relevant to the bot. There are tools which assist the developer with finding what they want by creating a memory image and providing various search tools. A countermeasure is to use address layout randomization, but a smart bot might be able to still find what they are looking for automatically.




  • It is possible to modify the game executable itself. In order to do this the bot developers need to be able to read and program in assembler, which isn't that hard with some practice. They then look for the code which handles the information they are interested in and rewrite it to pass it to their bot. A possible countermeasure from the perspective of the game developer is to use an obfuscator to make the game's assembler code less readable, but these are usually not good for performance and there are tools for many obfuscators which reverse their work.




  • And then there is the netcode. In an online game, the server sends the properties and positions of all objects in the game via network. The network data stream between server and client can be intercepted and analyzed. A popular tool for doing this is wireshark. When the developer reverse-engineered the netcode, they can write a bot which intercepts the network traffic just like Wireshark does and uses the information to make its decision. When the developer is more motivated, they can even develop a complete game client from scratch which implements the network protocol and plays the game without even having any graphical output. Such bots are very popular with gold farmers because without the graphics output the client is usually far more resource-friendly, which means they can run a lot of them at once on a small server.







1: Since you mention WoW, it's worth pointing out that the early and notorious WoWGlider botting program used direct memory access. Blizzard had a subprogram called Warden that was designed to detect and block outside programs from accessing WoW's internal game state. Since the bot program circumvented this protection and read the memory without permission, the 2006 lawsuit MDY v Blizzard was decided in favor of Blizzard on the grounds that the bot maker was encouraging and enabling its users to commit copyright infringement and violate the DMCA.


Changing background music smoothly


I've got five sounds now for a game I'm working on currently. In the game, you can fight against other civilizations in big battles, but you can also settle on planets in peace.


Some of the songs are more violent, while others are quite peaceful. The question is: what is the best practice for changing between the songs. Is it better if I just look "is it peaceful or not" when the old song ends and then play a new one or should I do that every single frame and change the songs immediately.


The first alternative would sometimes play silent songs in battles (because the song started before the battle and isn't finished yet) and the second one would switch between to different-fast songs properly at the wrong moments so the player would hear a cut.


So I'd like to know what is more natural for the player or if there is a different possibility.


PS: The songs are between 300 and 500 seconds long.



Answer



There are actually some fairly standard approaches for designing music playback in a game. When designing a music playback system, problems you face involve creating smooth transitions, ensuring there is enough variety, and creating a sense of interactivity with the music. Your question title, "changing background music smoothly" tells me your main concern is transitions so that's what I'll primarily be addressing for each method.


Method 1: Layers and Stems


One approach for creating smooth music playback systems in games, what Patrick Hughes called the "AAA way", is to build your music up in layers (also sometimes called stems) such that there's no single definitive version of the track. Instead, you might have a single base track running consistently, with melodic, rhythmic, harmonic variations that get played over it.



You usually (credit again to Patrick Hughes) build these around common motif that runs through each element layer in a piece of music, or even througout all music in the game. A good example of a non-melodic motif is Martin O'Donnell's use of the Phrygian scale in Halo games (http://www.1up.com/features/music-halo-reach). Normally, each of these component music tracks are aligned to be playing in sync on a timeline with each other. Although it is possible to create music layers that do not necessarily depend on a consistent tempo and synchronized timeline, or can work well in multiple tempo and timeline contexts.


Because each layer is designed to work together, it's entirely possible to have a single layered music track that just plays throughout the entire game, making slight transitions between layers within itself to signify game state changes.


Method 2: Branching


You say you have music tracks already produced, so this implies you've already got a specific direction in mind: branching music. With branching music, your primary concern is the transition between music tracks that have been specified to play at particular sections of the game. You can achieve variety by breaking your individual music segments down into loops that have a couple of different versions, so that the same version never plays twice in two iterations and doesn't always start out the same way.


One way to handle transitions in simple branching music is to write more music that purely acts as a transition from these existing music tracks to others. Even if it's not feasible to cover every possible music transition, you can also use the "connector tracks" to make a music track end early in the case where you're trying to avoid simple fade-in, fade-out music changes.


Method 3: CCC-Combo


It's also important to note that the two major approaches discussed here (layers and branching are what they're typically called) can coexist conceptually. "Branching" is such a simple term and description of what's happening that you could very well be branching between layered music systems. This often requires a semi sophisticated playback system, so you have to balance what's worth your time to implement.


Method 4: Pragmatism and Simpler Music Playback


And, of course, you could always just fade-in and fade-out your music as needed. No shame if that's what feels right, or it's not feasible to write connector tracks. Better this than hard cuts to completely unrelated piece of music--that would sound pretty awful.


I'd also like to address your "silent songs" idea. It's not bad, but what happens when you start playing one 300-second track for 5 seconds, then you get immediately into a state where you need to transition to another track? Waiting for the remaining 295 seconds to go by seems impractical if you really care about making that music transition.



However, if the music is purely background music, and its fundamental purpose is to provide to simply set an overall mood, then "simple background music list" is a perfectly legitimate way to think about it. At this point you are talking about a music playlist like you'd build in iTunes or Windows Media Player (is that still at thing?) so you should implement it with that in mind.


Further reading


To learn more about standard approaches for designing music playback in games, you should take a look at learning materials for two of the largest interactive audio middleware tools that see common use in the industry, FMOD and Wwise.


Wwise has good reference material on this page. The "Making Interactive Music for Games" article is especially good as it goes into further depth about the information I've written here. The FMODTV Youtube Channel has videos with Stephan Schutze that cover FMOD Studio as a whole--including the parts of it that can be used to design music playback systems. Learning how these tools approach this problem can help you think about how to address your own game's needs.


path finding - Tweaking AStar to find closest location to unreachable destination



I've implemented AStar in Java and it works ok for an area with obstacles where the chosen destination is reachable.


However, when the destination is unreachable, the calculated "path" is in no way to the closest location (to the unreachable location) but is instead some random path.


Is there a feasible way to tweak AStar into finding the path to the closest location to an unreachable destination?



Answer



Keep track of the node with the lowest EstimatedDistanceToEnd (ie. the lowest h(x)), and if no end-node is reachable to backtrack from, backtrack from that node instead.


ambiguity - Certain kinds of fish or certain kinds of fishes?




Below is an excerpt taken from the passage given at Passage Comprehension page.



Many scientists are working on safer and better ways to kill mosquitoes, but so far, there is no sure way to protect everyone in the world from their deadly bites. Mosquito nets can be placed over beds to protect people against being bitten. These nets help people stay safe at night, but they do not kill any mosquitoes. Mosquitoes have many natural enemies like bats, birds, dragonflies, and certain kinds of fish.



My doubt is regarding the bolded phrase. Is the bolded phrase correct?


Shouldn't it be either certain kinds of fishes or certain kind of fish.



Answer



Not at all. The reason is the way the phrase is constructed: the thing of which there are kinds is fish. You can say "kinds of fishes", but it would be redundant and a bit absurd, since "fish" is a common name referring to an entire species, and thus, referring to "all" the fishes already.


It is not an English thing, it is a common construction in several languages when describing groups of things. The thing itself is singular, and the properties referred of said thing (kinds, weights, heights, colours, whatsoever...) go in plural. This is because the actual subject is the property itself, "they" (since the property is referring to a group, and is therefore plural).



To put it simply, the phrase is actually like "Soldiers of England". Soldiers is the subject. So you could weirdly change it to "they are of england". Different kinds of fish, in the same way, could be substituted by "they are of fish". Which things are of fish? Different kinds.


word choice - Confusion regarding “to doing something” vs. “to do something”



I am always confused with the form of “to doing something”, e.g.:



I admitted to doing something.



vs.:



I admitted to do something.





Monday, November 19, 2018

comprehension - “save for” -- meaning?


Example with a context:



Earlier this evening, I sat in the Salt Lake Roasting Company, a gourmet coffee roaster in Salt Lake City, and, over several cups of hot, fresh, delightfully aromatic Costa Rican coffee, scribbled the notes for this introduction. It occurred to me that selecting an Access development book is much like choosing your next pound of coffee beans: Without some sort of guide, one Access book looks pretty much like the next save for differences in their tables of contents and covers, just as two pounds of coffee from different regions of the world seem indistinguishable but for slight variations in their aroma and appearance. This book is different from the typical Access books sitting right next to it on the bookshelf. Some of the reasons are:



How do you understand that expression? Does that mean something like never mind their differences in the tables of contents and covers?



Answer



Save for means the same as except for.


In this sense of save for, the word save suggests holding some items back, or setting some items aside so they don’t get involved in some activity. “I brought all of my best silverware to Karen’s Christmas party, save for a few delicate antiques.” In other words, you protected the old, delicate pieces of silverware by keeping them at home instead of bringing them to the party. A real example: “The fight went on until the whole Turkish squadron, save for the steamer, was destroyed.”


In the paragraph you quoted, the author is suggesting that as you look over the many books about Microsoft Access, their attributes blur together in your mind so you can't distinguish one book from another. But a few attributes are “saved” from getting blurred together: the tables of contents and the covers.



The metaphor of saving is mostly but not completely dead.


To my native American English ear, save for sounds old-fashioned.


How do I use the auxiliary "do" in questions?


Consider these two sentences:



Who left the door open?




and



Who do you want to speak to?



In the first question auxiliary do cannot normally be used, but in the latter question it can. Why is that so? What is it about the second sentence that requires auxiliary do that the first sentence doesn't have? Please include a few more examples of this pattern if possible.



Answer



These are called subject questions (as your first example) and object questions (as your second). Here we are talking about "do", so this is present simple and past simple tense. Let us take one example:


Paul wants to speak to him.

1) If we want to know who "him" is, "him" is the object and the question we will ask is an object question. There will be an auxiliary verb, which will come between the question word and the subject:



Who does Paul want to speak to?

2) If we ask a question about "Paul" (the subject), however, it will be a subject question, and then all we need to do is substitute the subject with a question word:


Who wants to speak to him?

Further reading with examples: in this grammar book


3) It is possible to add an auxiliary verb in subject questions, that has already been discussed here. To sum it up, it adds emphasis, as in:


A: Who wants to speak to him? Jack?
B: No.
A: Jim?

B: No.
A: Well, then who **does** want to speak to him?

More examples of that can be found in the link.


javascript - determine collision angle on a rotating body


update: new diagram and updated description


collision angle and body angle


I have a contact listener set up to try and determine the side that a collision happened at relative to the a bodies rotation. One way to solve this is to find the value of the yellow angle between the red and blue vectors drawn above. The angle can be found by taking the arc cosine of the dot product of the two vectors (Evan pointed this out). One of my points of confusion is the difference in domain of the atan2 function html canvas coordinates and the Box2d rotation information. I know I have to account for this somehow... SS below


questions:




  • Does Box2D provide these angles more directly in the collision information?

  • Am I even on the right track? If so, any hints?


I have the following javascript so far:


Ship.prototype.onCollide = function (other_ent,cx,cy) {

var pos = this.body.GetPosition();

//collision position relative to body

var d_cx = pos.x - cx;
var d_cy = pos.y - cy;

//length of initial vector
var len = Math.sqrt(Math.pow(pos.x -cx,2) + Math.pow(pos.y-cy,2));

//body angle - can over rotate hence mod 2*Pi
var ang = this.body.GetAngle() % (Math.PI * 2);

//vector representing body's angle - same magnitude as the first

var b_vx = len * Math.cos(ang);
var b_vy = len * Math.sin(ang);

//dot product of the two vectors
var dot_prod = d_cx * b_vx + d_cy * b_vy;

//new calculation of difference in angle - NOT WORKING!
var d_ang = Math.acos(dot_prod);

var side;

if (Math.abs(d_ang) < Math.PI/2 )
side = "front";
else
side = "back";

console.log("length",len);
console.log("pos:",pos.x,pos.y);
console.log("offs:",d_cx,d_cy);
console.log("body vec",b_vx,b_vy);
console.log("body angle:",ang);

console.log("dot product",dot_prod);
console.log("result:",d_ang);
console.log("side",side);
console.log("------------------------");

}


meaning in context - Right or left? When the teacher says: "If you look at the diagram on the left hand side, you will solve this question!"(In a position like this?)


● Right or left? When the teacher says:



"If you look at the diagram on the left hand side, you will solve this question!"




Is it the teacher's left hand side or students' left hand side?


Imagine, you are in a position like this:



Where is right? Where is left? (You can use the colours).




The example I have in mind is this Cardiac Muscle: Function & Main Parts – Histology | Lecturio. There is a speaker off-screen. Referring to this image, he says



enter image description here
And cardiac muscle has structures called intercalated disks, which if you look at the diagram on the left-hand side, it explains what these intercalacted disks actually are and what their functional role is.





Answer



When somebody is standing in front of a crowd and they say left or right, it's almost always in reference to the perspective of the crowd that is being addressed.


A teacher may turn and point to the blackboard, indicated something to the left or right as they are now facing.


In theatre, if an actor or director wants to talk about things from the perspective of people on the stage facing the audience, they use the phrases stage left and stage right (from Merriam-Webster). Note that that is not spoken to the audience; it's for stage direction behind the scenes and during rehearsals. The audience uses the normal words.


So, the assumption is normally the perspective of the audience.


But if it's unclear, clarifying language can be used.


unity - Mip Maps on 2D Sprite causing black line above. Why is this?


I am new to Unity. I'm trying it out and using Futile for a code-first approach, but still importing textures using the Unity system.


The problem I'm having is that when I use mip maps to scale large sprites down to smaller sizes without jagged edges, I'm getting a black line artefact above said sprites.


Hard to see


A little hard to see, but they're there. If I turn down the resolution, you can clearly see them:


Easier to see


These are my texture settings:



Settings


My question is, why are these black lines here? Is it a mistake I've made? Is it just a common side effect? How can I reduce these? Also, if this is the wrong approach, how can I use smooth sprites in a game with the ability for them to scale up smoothly?


Thanks!



Answer



There are many reasons why you may be getting those lines. I wrote a more detailed answer in here, but the bottom line is:



Do not do atlasing and mipmapping at the same time.



For 2D, in general, you don't want/need to do mipmapping. That's useful mostly in 3D where you don't know the size at which your textures will be rendered, but that's usually uncommon in 2D.


If you definitely have a texture that you will aggressively downscale, then don't include it in an atlas.



And I'd also recommend you turn anisotropy off. That's meant to give you better results when you're looking at big textures from extremely sharp angles, which simply doesn't happen if your game is 2D.


Sunday, November 18, 2018

tense - Is there a simple and clear way to explain the difference between past simple and present perfect?


I read (or do I say "have read"?) many rules for when to use the present perfect. I found them complex and hard to understand (or do I say "have found"?). I am finding it hard to apply these rules in real sentences.


Is there a simple and clear way to explain the difference between past simple and present perfect? If there is a simple explanation, please tell it! If there is no simple explanation, please tell why it is so complicated. Maybe if I knew why there is no simple explanation, that would help me understand what work I need to do in order to learn the difference.





unity - Enemies are penetrating in each other when following player


enter image description here


As you can see the image my enemy (when following my player), penetrate each other. How can i avoid it? I am using NevMeshagent to follow the player.


void Update () {
currentNavMeshAgent.destination = player.transform.position;
}


I have added a Rigidbody and a Collider to my enemy object but they are still penetrating each other



Answer



To avoid penetration, increase each NavMeshAgent's radius so it's equal to or larger than your agent's collider.


Saturday, November 17, 2018

2d - Restricting Maximum Velocity in Space


I'm making a top-down 2D space ship game in which you rotate and thrust. I'd like to impose a maximum velocity for different engine types, meaning that a certain engine can only get you going up to a certain speed.


But I'd also like the ship to be able to travel faster than that maximum velocity, say if it were sent flying by a collision with a fast-moving asteroid.


I can't naively have the engines only apply impulse if the ship is moving at less than its maximum speed -- otherwise if an asteroid sent you flying to the right, you couldn't deliberately slow down because that would involve applying an impulse to the left.


But I'm not restricted to cardinal directions. If the ship is moving too fast to the right, I don't want it to accelerate to the right, but I would like it to be able to curve upward, which might involve applying some kind of impulse at say a 15 degree angle.


My other thought was to cap the maximum velocity of the ship at the maximum velocity of the engine, but then an asteroid collision could send you flying no faster than you engine's maximum speed, and that's undesirable as well.


How might I go about designing a system that allows one to reach velocities no higher than a set maximum from their own impulse, but still be able to steer their ship at higher velocities and still actually attain those higher velocities from external means?


Edit



Let's say my maximum velocity is 50 m/s. I'm traveling at 50 m/s at a 15 degree angle, which means my x velocity is 48.3 and my y velocity is 12.9. The ship is facing at a 30 degree angle (even though it's traveling along a 15 degree vector).


When I press the thrust button, I want the ship to trend toward that 30 degree angle of travel. Which means that its current angle of travel must be altered in some fashion. Right now I do so by applying impulses. But if I apply an impulse at a 30 degree angle, the ship's velocity will exceed is maximum (a good portion of that impulse is in the same direction as we're already going).


If I don't allow that impulse to be applied, the player can't adjust their course at all while they're moving too fast. And I'm not sure how to determine which components of an impulse would change a ship's velocity's angle without increasing its length.



Answer



This problem is a bit difficult to think about because it's unphysical -- engines have a thrust which equates to acceleration and not top speed. So I think to fully answer this question, you need to remove it from a physical framework and just think of it in terms of vectors.


To be clear, I will use "speed" whenever I am talking about the overall quantity of movement of the ship, and "velocity" when there is some directionality associated with it.


You can use the directionality of velocity to your advantage here. Your engine impulse can only add velocity in the direction of impulse if the velocity in the direction of impulse is below the "engine speed" rating. You need to consider vector addition here for this to work the way you want it to. If the player impulses in a direction that is not orthogonal to direction of motion, then ONLY the amount of impulse applied in the orthogonal direction will actually increase the velocity in that direction, which means that you can change direction. To disallow the player from actually increasing speed in this situation, you need to remove velocity from the previous direction of motion so that the speed stays the same (using that you can calculate speed by adding the orthogonal velocities in quadrature).


This would allow for maneuvers at higher than engine speed given that your original speed is over engine speed due to some external mechanism, but it would not allow for acceleration past engine speed in any given direction.


EDIT


Here's an example of what I mean (using the conditions you included in your edit):



You would presumably have an acceleration value of some sort from your engine specifications. Let's just say it's 1 m/s/s for the sake of argument. Let's say you press the thrust key and hold it down for 1s at 30 degrees while your ship is travelling at 50 m/s at 15 degrees (giving vx = 48.296 m/s and vy = 12.941 m/s). You would then need to apply a 1 m/s change somehow, while still maintaining 50 m/s overall speed. So, first we must figure out what part of that 1m/s is orthogonal to your original direction and then decompose the 1 m/s along that basis.


If you draw it out (I'm not sure how to draw here) you can see that you just need to undergo a 15 degree rotation, so the direction of thrust along your current vector is 1 m/s * cos(15)=0.966 m/s and the direction orthogonal is 1 m/s * sin(15)=0.259 m/s. Here comes the "difficult" part: you now need to calculate the new direction based on these values. We already determined that the thrust along the vector will not affect anything, so we can discard the 0.966 m/s change and just apply a 0.259 m/s change in the orthogonal direction.


Since we have forced acceleration to only be orthogonal, we know that this is a "circular" change in velocity (it only changes direction and NOT speed -- exactly what you want!). In this case, the orthogonal direction is 15 + 90 = 105 degrees, so decompose that into your original x-y basis and you get that dvx = 0.259 m/s * cos(105) = -0.067 m/s and dvy = 0.259 m/s * sin(105) = 0.250 m/s. It's important that you get your angles right, because that negative sign in dvx is how the magnitude stays the same! Put this together and your resulting velocity after 1s of thrust at 1 m/s/s is vx = 48.296 m/s - 0.067 m/s = 48.229 m/s and vy = 12.941 m/s + 0.259 m/s = 13.200 m/s which gives you vt = sqrt(48.229*48.229 + 13.200*13.200) m/s = 50.003 m/s which is 50 up to the precision we calculated (3 decimal places). The computer will maintain float or double precision, but you still might want to cap it at previous speed manually or those rounding errors will accumulate.


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