Tuesday, May 31, 2016

xna - How do I solve my resolution problems?


I am developing a game with XNA, and I am having trouble with resolutions. For now, I have only implemented the main menu, but I want to make a game that is independent of the resolution. As I am a beginner, I haven't taken into account the resolution, so far. When I changed the resolution, it gave me a real headache. The background image that I use has a 1920x1080 resolution, so it has an aspect ratio of 16:9. The initial resolution was 800x600, so the background image looks stretched. The same happens with resolutions with aspect ratio 4:3 (e.g. 640x480, 1024x768, etc.).


Before posting this question, I searched for information on the Internet. I found "XNA 2D Independent Resolution Rendering", and other similar solutions. The solution offered seems perfect for me, at first, because I wasn't thinking of using two resolutions; one internal, for drawing, and one that corresponds to the size of the window. However, I have been observing some problems.




When I enable fullscreen mode, and its resolution is lower than the desktop resolution, the game doesn't stretch the resolution to fill the entire screen. This makes the game draw at the center of the screen, but with a black border on both sides of the screen.


enter image description here




The aspect ratio of my background image is 16:9, however, the resolutions that I am trying have an aspect ratio of 4:3. With the page solution, I have the same problem; the background image seems to be stretched. I researched the code, to find a solution, and changed the RecreateScaleMatrix() function to this:


private static void RecreateScaleMatrix() 
{

_dirtyMatrix = false;
float aspect = 16.0f / 9.0f;
_scaleMatrix =
Matrix.CreateScale((float)_device.GraphicsDevice.Viewport.Width / _virtualWidth,
(float)_device.GraphicsDevice.Viewport.Height / _virtualHeight, 1f) *
Matrix.CreateScale(1, EngineManager.GameGraphicsDevice.Viewport.AspectRatio /
aspect, 1) * Matrix.CreateTranslation(0, (_device.GraphicsDevice.Viewport.Height -
(_device.GraphicsDevice.Viewport.Height / aspect)) / 4.0f, 0);
}


This seems to have solved the problem, but only on certain resolutions ,and further reducing the rectangle which show the final result.




I have been thinking about these problems all day, and I realized that without knowing the exact resolution of the image to draw, in advance (independent of aspect ratio), is almost impossible to draw an image clearly.


How do I solve my resolution problems?




unity - Fading Text in one character at a time


I'm a Unity game developer. I have a bit of a conundrum. I have two enumerators, one that displays text one character at a time, and the other takes the whole text and fades it in over time:


private IEnumerator FadeTo(float aValue, float tValue)

{
float alpha = GameText.GetComponent().color.a;
for (float i = 0; i < 1.0f; i += Time.deltaTime / tValue)
{
Color alphaChange = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, i));
GameText.GetComponent().color = alphaChange;
yield return null;
}
}
private IEnumerator CharXChar(string text)

{
for (int i = 0; i < text.Length; i++)
{
yield return new WaitForSeconds(0.1f);
GameText.GetComponent().text = GameText.GetComponent().text + text[i];
}
}

The problem is, I do not know how to get the FadeTo enumerator to modify each character individually. I just need a step in the right direction. Any help would be greatly thanked.



Answer




Here's a very ugly solution using rich text. It wraps a tag around every letter, then updates the alpha values as the fade progresses along the string.


I'm using the StringBuilder to cut down on unnecessary string allocations, but this still generates one new allocation every frame while the fade is running (fortunately it's always the same size so it shouldn't cause much trouble).


There are probably more efficient options, like positioning a second text element to hold the fading characters, but this was quick and dirty:


using UnityEngine;
using UnityEngine.UI;
using System.Collections;

[RequireComponent(typeof(Text))]
public class TextFade : MonoBehaviour {


[Tooltip("Number of seconds each character should take to fade up")]
public float fadeDuration = 2f;

[Tooltip("Speed the reveal travels along the text, in characters per second")]
public float travelSpeed = 8f;

// Cached reference to our Text object.
Text _text;

Coroutine _fade;


// Lookup table for hex characters.
static readonly char[] NIBBLE_TO_HEX = new char[] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'A', 'B',
'C', 'D', 'E', 'F'};

// Use this for initialization
void Start () {

_text = GetComponent();

// If you don't want the text to fade right away, skip this line.
FadeTo(_text.text);
}

public void FadeTo(string text)
{
// Abort a fade in progress, if any.
StopFade();


// Start fading, and keep track of the coroutine so we can interrupt if needed.
_fade = StartCoroutine(FadeText(text));
}

public void StopFade() {
if(_fade != null)
StopCoroutine(_fade);
}


// Currently this expects a string of plain text,
// and will not correctly handle rich text tags etc.
IEnumerator FadeText(string text) {

int length = text.Length;

// Build a character buffer of our desired text,
// with a rich text "color" tag around every character.
var builder = new System.Text.StringBuilder(length * 26);
Color32 color = _text.color;

for(int i = 0; i < length; i++) {
builder.Append(" builder.Append(NIBBLE_TO_HEX[color.r >> 4]);
builder.Append(NIBBLE_TO_HEX[color.r & 0xF]);
builder.Append(NIBBLE_TO_HEX[color.g >> 4]);
builder.Append(NIBBLE_TO_HEX[color.g & 0xF]);
builder.Append(NIBBLE_TO_HEX[color.b >> 4]);
builder.Append(NIBBLE_TO_HEX[color.b & 0xF]);
builder.Append("00>");
builder.Append(text[i]);

builder.Append("");
}

// Each frame, update the alpha values along the fading frontier.
float fadingProgress = 0f;
int opaqueChars = -1;
while(opaqueChars < length - 1) {
yield return null;

fadingProgress += Time.deltaTime;


float leadingEdge = fadingProgress * travelSpeed;

int lastChar = Mathf.Min(length - 1, Mathf.FloorToInt(leadingEdge));

int newOpaque = opaqueChars;

for(int i = lastChar; i > opaqueChars; i--) {
byte fade = (byte)(255f * Mathf.Clamp01((leadingEdge - i)/(travelSpeed * fadeDuration)));
builder[i * 26 + 14] = NIBBLE_TO_HEX[fade >> 4];

builder[i * 26 + 15] = NIBBLE_TO_HEX[fade & 0xF];

if (fade == 255)
newOpaque = Mathf.Max(newOpaque, i);
}

opaqueChars = newOpaque;

// This allocates a new string.
_text.text = builder.ToString();

}

// Once all the characters are opaque,
// ditch the unnecessary markup and end the routine.
_text.text = text;

// Mark the fade transition as finished.
// This can also fire an event/message if you want to signal UI.
_fade = null;
}

}

Here's an example of the effect:


Animation showing text fading in character by character.


Monday, May 30, 2016

architecture - How to synchronise the acceleration, velocity and position of the monsters on the server with the players?


I'm building an MMO using Node.js, and there are monsters roaming around. I can make them move around on the server using vector variables acceleration, velocity and position.


acceleration = steeringForce / mass;


velocity += acceleration * dTime;


position += velocity * dTime;


Right now I just send the positions over, and tell the players these are the "target positions" of the monsters, and let the monsters move towards the target positions on the client with a speed dependant on the distance of the target position. It works but looks rather strange.



How do I synchronise these properly with the players without looking funny to them, taking into account the server lag?


The problem is that I don't know how to make use of the correct acceleration/velocity values here; right now they just move directly in a straight line to the target position instead of accelerating/braking there properly. How can I implement such behaviour?



Answer



There are several things you could do to reduce the visible effects of lagging. Just some ideas:




  1. Send the current acceleration, velocity and position values to the client, and let the client calculate the new velocities and positions until it receives a new data package.




  2. Avoid using frequently changing acceleration.





  3. You should consider defining states of the characters. For example: When a monster attacks, it has 2 acceleration, 0 starting velocity (vector pointing towards the player), and this state lasts for 2 seconds. You can send the identifier of the monster's current state, and the client will know the speed and acceleration values, and will know that it's gonna last exactly for 2 seconds. This way the client can draw the movement smoothly. If something happens in those 2 seconds, eg. the monster dies, then the client receives the new state ("Dying") and can show the animation of that state. Also, define default state changes. For example, a monster will have the "Dead" state as default after the "Dying" state. If "Dying" lasts for 3 seconds, and the client doesn't receive any updates for 3 seconds, your monster isn't gonna get stuck in the "Dying" state, but will die properly on the client side as well.




  4. You could implement some kind of lag compensation on the client side. For example, a small delay to the actions of the player, or effects of spells etc. If the player pushes the jump button, he won't jump immediately, but only after 40 milliseconds or so. The packet gets sent to the server with a timestamp, and forwarded to another player if necessary. The server and the other player's client will know that the actual jumping should be displayed only at Timestamp + 40 milliseconds. You can make this work with most actions without making the delay frustratingly high.




  5. Further reading:





https://stackoverflow.com/questions/1448997/do-good-multiplayer-mmo-clientserver-games-use-latency-within-movement-calcula


Low traffic client synchronization with server in MMO


How do I keep an MMO synchronized?


present perfect - I'm being corrected "I had a headache yesterday" vs "I have had a headache yesterday"




My friend asked me just today, "Hey, how are you?"


I said, "Tired, sleepy, and can't concentrate on my work."


He then asked, "Why so?"



Here is where the interesting part starts.



I said, "I have had a headache yesterday"



He said that I should have said "I had a headache yesterday" instead of "I have had a headache yesterday"



But all grammar books say that with Present Perfect + Past Tense we mean an action that continues into the present; has consequences in the present.


I didn't want to just tell the fact that I had a headache but I implied that that was the reason I was "Tired, sleepy, and can't concentrate on my work."


Who is right?



Answer



Yesterday refers to time in the past. If the headache has passed, you no longer have it:



I had a headache yesterday.



If your headache began yesterday and you still have it:




I have had a headache since yesterday.



Let's say you've acted grumpily towards someone and you want to apologize:



I'm sorry. I have had a bad headache all day.



You still have the headache. It began in the past (perhaps this morning) and has persisted.


Merely a causal connection between a past event and the present is not sufficient grounds to use the present perfect. If there is a time phrase relegating the action to the past, you cannot use the present perfect in that clause. If the time phrase excludes the present, the present perfect cannot be used in that clause.



He robbed a bank five years ago. And now he is in prison.



He robbed a bank early this morning, and he will go to prison for it.


He robbed a bank in his youth and he went to prison for it.



But contemplate this:



You have robbed a bank and now you are going to prison.



There is no time phrase relegating the robbery to the past, no time phrase which excludes the present; the speaker, by choosing the present perfect, is expressing a relationship of the past event to the present.


Here's how you might translate it on a semantic level:


He robbed a bank ~ he was a bank robber



He has robbed a bank ~ he is a bank robber


c# - Overcoming float limitations for planet-sized worlds in Unity


As far as I know, going further than 1M units from the world origin in Unity is hardly possible due to floating point precision issues.


Making a world more than 1M units in radius would require either using double vars for coordinates or utilizing some space division technique to divide a massive scene into hierarchical chunks with the smallest of them being around 10 000 units, i.e. each world-space position would be expressed by the chunk hierarchy the object's in and a bunch of float vars representing its local position (and possibly rotation and scaling) inside the last chunk.


Either way, doing this would require implementing a completly new coordinate system, so I'd like to know whether or not that is possible in Unity, and if so, how may I make it work with existing Unity systems like physics and so on.


P.S I can't just move the world into origin as the player moves since I want to have things going on simultaneously around the planet.


Thanks!



Answer



You're thinking in very static terms.


Just because an object is half a world away doesn't necessitate any issues. If entity coordinates are stored relative to chunk rather than relative to world, this is trivial to achieve. Welcome to the way you'd have to do it if you were writing a voxel world in native code.



So let's assume a concept called locales. It's a set of chunks that are in close proximity to one another. What matters is the float space internal to a given locale never exceeds the safety limit. You need to determine what your discrete processing locales are, start by taking all chunks that fall within a radius of the position of entity n (could be the player or something else). In my current engine, I make sure that if even one chunk of two different locales is overlapping, that these locales merge into one locale / set of unique chunks. This ensures that you never process all the entities in any single chunk more than once, in a given frame.


Now that you have your locales/chunk-sets, you can perform game logic on them and their contents. And it doesn't matter how far they are away from the player or from origin. What matters is that you get a chunk that is roughly central to each set, treat that as the origin i.e. float [0.0,0.0,0.0], and work your way outward from there. Given typical view range in a game, I guarantee you that you will never need to see more than a few kms, which is very doable with float, without serious issues.


Aside from Unity, one option is to write an engine from scratch, I guess, and use something like libfixmath, where you can still use decimal points but because they do not float, they will never have these accuracy issues. But I guarantee you will need chunks and locales for other reasons, so it's probably not worth the effort.


2d - How do I use the dot product to get an angle between two vectors?


I am learning to use normalized vectors in my games.



I've learned that in order to know the angle between two vectors, I can use the dot product. This gives me a value between -1 and 1, where



  • 1 means the vectors are parallel and facing the same direction (the angle is 180 degrees).

  • -1 means they are parallel and facing opposite directions (still 180 degrees).

  • 0 means the angle between them is 90 degrees.


I want to know how to convert the dot product of two vectors, to an actual angle in degrees. For example, if the dot product of two vectors is 0.28, what is the corresponding angle, between 0 and 360 degrees?



Answer



dot(A,B) = |A| * |B| * cos(angle)
which can be rearranged to

angle = arccos(dot(A,B) / (|A|* |B|)).


With this formula, you can find the smallest angle between the two vectors, which will be between 0 and 180 degrees. If you need it between 0 and 360 degrees this question may help you.




By the way, the angle between two parallel vectors pointing in the same direction should be 0 degrees, not 180.


tense - Implications of past perfect


I know have been does, but does had been also imply some ongoing action?


Do these mean the same?




"I just wanted to make sure it was you because I had/have been getting weird emails."



Can had been imply that you are still getting some since it doesn't really say anything about you not getting any more weird emails?



"If you asked him to do the chores, he should be doing them right now, since he had/has decided to help you out more."



Can both "had decided" and "have decided" imply that his decision is still current? Or do you have to choose one thing over the other? I think present perfect would be wrong in these examples, but I'm not sure if past perfect will imply the same meaning.




java - Storing data for a pokemon like game


The game I'm developing is close to Pokemon. How should I store the data? I am currently thinking of text files where I save the map and have a corresponding textfile for the trainers and their teams on the "current" screen. However this leaves me with a LOT of textfiles.


At the moment I'm thinking of something like this, however I haven't coded this yet so I can still easily change this.


@Trainer;5;
@Pokemon;12;1;3;4;6;
@Pokemon;13;1;2;5;
@Pokemon;13;1;4;5;
@Pokemon;11;1;3;5;

@Pokemon;16;1;2;7;
@Trainer;3
@Pokemon;13;1;4;5;
@Pokemon;11;1;3;5;
@Pokemon;16;1;2;7;

Where the first column is the "type" of the entry. If the first is Trainer the second is his number of Pokemon. If the first is Pokemon the second is the level, the third the type, the fourth/fifth/sixth the IDs of his attacks. (How should I store the attacks? A seperate textfile where I just store the attacks?)


I am currently finding myself with having such a huge amount of data that I'm starting to wonder wether I should be using a Database instead?


Edit: Using Java(LWJGL).




grammar - Grammatical function of "at best" idiom


Dictionaries state that "at best" is an idiom. But, what is the grammatical function of "at best" (for example, in the below sentences?)





  • Their response to the proposal was, at best, cool.

  • The government's response seems to have been at best confused and at worst dishonest.

  • If he drops the course now, at best he’ll get an incomplete, and he could fail.



Thanks



Answer



In order to analyze this, it would be easier to start with one of the more standard definitions:




  • taking the most optimistic view

  • in the most favourable interpretation

  • under the most favourable condition


Then substitute the phrase for the definition:



  • Their response to the proposal was, in the most favorable interpretation, cool.

  • The government's response seems to have been in the most favorable view confused and in the least favorable view dishonest.

  • If he drops the course now, under the most optimistic outcome he’ll get an incomplete, and he could fail.



Now you can see it as a prepositional phrase. I think (but am not 100% sure unless someone supports this) that it would function as a disjunct adverbial. See http://www.linguisticsgirl.com/using-prepositional-phrases-disjunct-adverbials/


In the last sentence, there seems to be some element of uncertainty. Suppose it was a teacher who caught a student cheating. The teacher could give an incomplete, but the administration might fail him. In that case the teacher would say 'but':



  • If he drops the course now, under the most optimistic outcome he’ll get an incomplete, but he could fail.


Sunday, May 29, 2016

phrase request - How to say "the answer to your question is:" shortly


Somebody wrote me an email which also contained a question.



I replied to his email, and now I want to answer the question.


What phrase can I use to prefix my answer?


I thought of: "The answer to your question is X", or "About your question, the answer is X", but this sounds too cumbersome.


I am sure I heard a shorter phrase for presenting an answer to a question. What's the correct phrase?




c# - Smoother object movement in Unity?


I'm using this code in my script to move a gameobject:


void Update () {

// Move the object forward along its z axis 1 unit/second.
transform.position = new Vector2(transform.position.x , transform.position.y - 0.2f);


}

On screen the movement is a bit jaggy and not fluent.


Is there a different approach?


Hint: Please do not suggestion to use rigidbody functions since adding rigidbody would disrupt everything I did.


Can I use FxedUpdate?


Mirza



Answer



You can use Update method and just multiply velocity with Time.deltaTime. But when you need more complex movement than "move on const velocity" better use both Update and FixedUpdate. Method FixedUpdate should chooses current velocity for object. For example, if you want to move object to specified position FixedUpdate method should calculates velocity depends on current object position and target position. Method Update in this case will be used for smoothing movement, it will not change real position of object but recalculates each time. Here example:


private Vector3 fixed_position;

private Vector3 velocity;

void FixedUpdate() {
// apply previous velocity
fixed_position += velocity * Time.fixedDeltaTime;

// calculate new velocity
velocity = new Vector3(0.0f, 0.0f, 1.0f);
}


void Update() {
// recalculate smoothed position of object
transform.position = fixed_position + velocity * (Time.time - Time.fixedTime);
}

Saturday, May 28, 2016

unity - Set the start orientation of the gyroscope to initial phone orientation


I am making a mobile VR project in Unity, and I have a 360-degree video that starts playing where I can look around using a VR headset.


I am trying to set the start rotation of the video to the same rotation as my phone. So no matter where I look when I start the video, that should be my start rotation. I used Input.gyro.attitude in the start but that did not fix my problem. I think I am using it wrong.


This is my code (on the camera inside the sphere):


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;

public class Gyroscope : MonoBehaviour
{
private bool gyroEnabled;
private Gyroscope gyro;
private GameObject cameraContainer; //A camera container for my main camera
private GameObject videoSphere; //The sphere my video is in
private Quaternion rot;


private void Start()
{
videoSphere = GameObject.FindGameObjectWithTag("Video");
cameraContainer = new GameObject("Camera Container");

gyroEnabled = EnableGyro();

cameraContainer.transform.position = transform.position; // put the cameracontainer into the sphere
cameraContainer.transform.rotation = Input.gyro.attitude; // here I want to set the cameracontainer to the rotation of my phones gyroscope
transform.SetParent(cameraContainer.transform); // make my main camera a child of the camera Container


videoSphere.transform.localRotation = cameraContainer.transform.rotation; // Here I wanted to set my sphere rotation to the camera rotation
Debug.Log(videoSphere.transform.localRotation);
}

private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
Input.gyro.enabled = true; // turn on my gyroscope


cameraContainer.transform.rotation = new Quaternion(0, 90, -90, 0); // rotate my camera container so the video shows good
rot = new Quaternion(0, 0, 1, 0); // set the variable rot so that you can turn your device
return true;
}
return false;
}

private void Update()
{

if (gyroEnabled)
{
transform.localRotation = Input.gyro.attitude * rot; //this makes you turn the device and it recognizes the input of the phones gyroscope
}
}
}


prepositions - "on" 7th Street and 8th Avenue


I live on 7th Street and 8th avenue.


What does it mean? How can you live on two streets?



Answer



It means, literally, that you live in a building on the corner, at the intersection of the two streets; but it is sometimes used a little more loosely to mean near the intersection.



How you express an address depends to some extent on context. If you are trying to communicate what part of the city you live in, a single street name may be uninformative, since a street may be very long and pass through many very different neighborhoods. “34th and Vine” will pin things down for anyone who knows the city and wants to know what neighborhood you live in, or how to get there and how long it will take.


Some similar expressions are



I live on 7th Street, at 8th Avenue.
I live at 7th Street and 8th Avenue.
I live at 7th and Market. (this obviously won't work if the streets in both directions are numbered)
I live on 7th Street, just off 8th Avenue.
I live on 7th Street, between 8th and 9th Avenue.
I live on 7th Street, two doors down from 8th Avenue.
I live in the 800 block of 7th Street.




word usage - How to use "yet"?


Yet another question about yet, It's really confusing!


Please help me parse this phrase:



Be honest yet witty




At school, we used to use yet in the past perfect[if I remember] Like when we say : he didn't came yet


But I found numerous of uses of yet like in headlines:



Yet another mathematical problem.



And so on,so how to use "yet"?



Answer



Like many words, "yet" has several definitions.


It can mean "but" or "even though". It is generally used when expressing the idea that thing 1 is true, but thing 2 is also true. "Be honest yet witty" means "be honest, but at the same time be witty".



It can be used to refer to an event which as not taken place as of a specified time. It is generally used when you expect the event to happen eventually, or when you are still waiting for the event. "He hasn't arrived yet" means that, as of this moment, he hasn't arrived, but it implies that we do expect him to arrive sooner or later. If you don't expect him to arrive at all or you've given up waiting, you would leave off the "yet" and simply say "He hasn't arrived."


It can mean "even more" in phrases like "yet another" or "yet more". This is usually used as an intensifier. "Yet another mathematical problem" means you've already seen another, and now here is one more. It is typically used when you'd expect the quantity already seen to be enough. Depending on context getting "yet another" might be good or bad. Like, "Oh, yet another rude jerk to deal with", versus, "Oh, yet another delicious candy bar!"


time - The difference between "as" "when" and "while"


What's the difference between "as", "when" and "while"?



The doorbell rang as/when/while Anna was asleep.



Which is right and why?



Answer



While is used only about a continuous state, and another event or state that happens during that time. It does not imply or refute causality.




The doorbell rang while I was making dinner. - single
I listened to the radio while i was making dinner. Continuous



When implies a causal relationship between two things: when X happens Y happens. It can be used about a single event, an intermittent state or a continuous state



Please come and see me when you are free. - single
When the red light is showing, you can't cross the road. - intermittent (whenever)
When we were young, life was simpler. - continuous




When as is used about time, it implies two events or states happening by chance at the same time



I saw her as I was leaving. - event
The doorbell rang as she slept. - event/state
The sun was setting as the boat sailed away. - state/state



As @Peter pointed out, as can also mean because.



The phone rang as she was sleeping. (time)
She didn't answer the phone, as she was sleeping. (because)




The best word to use in your example is while. When is not suitable because there is no causality. As is possible and clear in this case, but may be ambiguous in similar situations.


c# - Texture2D.SetPixel method behaving weirdly in game province creation


I have been trying to implement a province system in Unity. I am trying to read the provinces from an image file, store their coordinates in a province, and use those coordinates to generate a texture and a 2D sprite for the province to be displayed on the screen at its appropriate world coordinates. Games like Risk, and many strategy games that rely on world maps to function use this approach. So far, I have the following code to parse the image from the province.png file I have created.


public class ProvinceReader()
{
public static void Read()
{

Texture2D provinces = MapImageCache.province_tex;
for(int x = 0; x < provinces.width; x++)
{
for(int y = 0; y < provinces.height; y++)
{
Color32 color = provinces.GetPixel(x,y);
ProvinceData province = null;
if(MapInstance.ColorCodedData.TryGetValue(color, out province))
{
province.AddPoint(x, y);

//TODO: Check if the neighboring pixels are of different colors. If so,
//add the pixel to the 'province border' pixels. The, get the province at
//the checked pixel position and store the x,y coordinate in a dictionary
//IDictionary>.
}
else
{
//MapInstance.Instance.ColorCodedData.Add(color, new ProvinceData());
}
}

}
foreach (ProvinceData prov in MapInstance.Instance.ColorCodedData.Values)
{
GameObject newProv = new GameObject();
newProv.AddComponent().SetData(prov);
newProv.AddComponent().sprite = prov.GenerateSprite();
}
}
}


public class ProvinceData
{
private List points = new List();
private List xPoints = new List();
private List yPoints = new List();
private Sprite image;

public Sprite GenerateSprite()
{
int minX = xPoints[0], minY = yPoints[0];

int maxX = xPoints[0], maxY = yPoints[0];
for(int i = 0; i < xPoints.Count; i++)
{
int xval = xPoints[i], yval = yPoints[i];
if(xval < minX) minX = xval;
else if(xval > maxX) maxX = xval;

if(yval < minY) minY = yval;
else if(yval > maxY) maxY = yval;
}

int width = (maxX - minX) + 1, height = (maxY - minY) + 1;
Texture2D m_tex = new Texture2D(width, height);

for(int i = 0; i < xPoints.Count; i++)
{
int xval = xPoints[i] - minX, yval = yPoints[i] - minY;
m_tex.SetPixel(xval, yval, new Color32(0, 123, 20, 255)); //I want to display the province on screen in green
}
m_tex.Apply();
this.image = Sprite.Create(m_tex, new Rect(0, 0, width, height), Vector2.zero, 1f);

return image;
}
public void AddPoint(int x, int y)
{
xPoints.Add(x);
yPoints.Add(y);
points.Add(new Vector2((float)x, (float)y));
//Also save whether it is a border point.
}
}


I have a black (0,0,0) province in the center of the texture in my png file:


enter image description here


And I am trying to read it. I loaded it into my MapInstance.Instance.ColorCodedData and ensured the data is valid. I loaded the png into a Texture2D and ensured the image was set up properly.


I am getting the following on my screen when I start the game:


enter image description here


I did some experimenting, and used Debug.Log to record a list of points. The largest point in the province that matches the province color is (x,y) => (643, 290). The smallest is (x,y) => (627, 281). I recorded the final value of "width" and "height", in the ProvinceReader.Read() method using Debug.Log(); The value was 1 when I explicitly subtracted the minimum of each value from the maximum of each value. So, I should have gotten (width, height) => (16, 9), but when I record these values I get 1. Which is weird.


I then changed the width and height values arbitrarily to 200,200 to see what happens, and I just get a 200x200 version of the above sprite.



Why is the sprite doing this? How can I solve it? If you need any more information, please let me know and I will include it.




Answer



public Sprite GenerateSprite()
{
int minX = xPoints[0], minY = yPoints[0];
int maxX = xPoints[0], maxY = yPoints[0];

for(int i = 0; i < xPoints.Count; i++)
{
int xval = xPoints[i], yval = yPoints[i];


if(xval < minX) minX = xval;
if(xval > maxX) maxX = xval;
if(yval < minY) minY = yval;
if(yval > maxY) maxY = yval;
}
int width = (maxX - minX) + 1, height = (maxY - minY) + 1;
Texture2D m_tex = new Texture2D(width, height);

for(int i = 0; i < xPoints.Count; i++)
{

//This is the modified code.
int worldX = xPoints[i];
int worldY = yPoints[i];
int xval = maxX - worldX;
int yval = maxY - worldY;

m_tex.SetPixel32(xval, yval, new Color32(0, 123, 20, 255)); //I want to display the province on screen in green
}
m_tex.Apply();
this.image = Sprite.Create(m_tex, new Rect(0, 0, width, height), Vector2.zero, 1f);

return image;
}

This code fixes the error. For whatever reason, the else when I was setting my max and min values was screwing things up. I was also forgetting to convert the x and y values into the coordinates of the new texture.


Phrase meaning: every now and then vs every once in a while


I would like to know whether there is a difference in meaning of the following phrases:
1. Every now and then;
2. Every once in a while. I know that they both mean occasionally, but is that all? There are no any other differences?



Answer



Nope, there is no real difference that I can see. I'd love to see an example, in context, where there is a difference in meaning, but I'm not seeing one at all. Further, I would say that the two phrases are equivalent as far as how commonly they are used and how easily they will be understood.


At this point, I will say that they are interchangeable.



Friday, May 27, 2016

lighting - How do I blend 2 lightmaps for day/night cycle in Unity?


Before I say anything else: I'm using dual lightmaps, meaning I need to blend both a near and a far.


So I've been working on this for a while now, I have a whole day/night cycle set up for renderers and lighting, and everything is working fine and not process intensive.



The only problem I'm having is figuring out how I could blend two lightmaps together, I've figured out how to switch lightmaps, but the problem is that looks kind of abrupt and interrupts the experience.


I've done hours of research on this, tried all kinds of shaders, pixel by pixel blending, and everything else to no real avail. Pixel by pixel blending in C# turned out to be a bit process intensive for my liking, though I'm still working on cleaning it up and making it run more smoothly. Shaders looked promising, but I couldn't find a shader that could properly blend two lightmaps.


Does anyone have any leads on how I could accomplish this? I just need some sort of smooth transition between my daytime and nighttime lightmap. Perhaps I could overlay the two textures and use an alpha channel? Or something like that?




meaning - How do you say that tree rings (are - will be) closer if there isn't much rain [in a year]?


Which of these sentences is true?



  • If there is not much rain in a year, the rings in a tree are close together OR

  • If there is not much rain in a year, the rings in a tree will be close together



If I removed "in a year" from the sentence would this make any difference?


A picture for illustration:


Rings in a tree


thanks ..



Answer



Your first sentence is correct. It's an example for Conditional Zero.


You use conditional zero when talking about something which is true in general. You can tell from the distance between the rings whether there was a lot of rain or not. This is always true.


The pattern for Conditional Zero is:


If + Present Simple, Present Simple


You can replace if with when or if not with unless in conditional zero. For example:



Unless there is much rain in a year, the rings in a tree are close together.



Here's a link to an overview on Wikipedia about all conditionals in the English language.


For the sake of completeness, "will + inf" as you use it in the second sentence is used in Conditional 1. As you can read on Wikipedia, Conditional 1 is about "consequences of a possible future event".


difference - A similar term to "paga fantas"


In my country, we use the informal term "paga fantas" which refers to a man who buys stuff or is willing to get anything for a girl with the intent of seducing her.


In some particular cases, a man who does this only intends to have sex with a girl, therefore he makes a great effort to buy a girl expensive stuff so that she accepts having sex with him.


Having said that, the purport of "paga fantas" doesn't refer to the following English terms:


Don Juan, Lothario, Prince Charming, Cocksman, Ladies' man, Lady-killer, Philanderer, Playboy, Seducer, Sheik, Womanizer, Philander, Skirt-chaser.


I would appreciate your valuable help in advance.




"I will come by the train" vs. "I will come by train" - do we need the article here?



I will come by the train.



Is it correct or we need to remove "the". Give reason also.



Answer



When referring to a mode, the article is omitted:




They arrived by boat.


We will ship this item by air.


We will go there by train.


The politician communicated with his base by tweet.


The train conductors union is on strike so we will have to go by bus.



Thursday, May 26, 2016

Verb tenses when asking a question


How can I establish time period when trying to ask someone about a question that was asked some time ago?




I asked you a question in my last email, but I wasn't sure (this is happening now) if it went through.



My asking took place sometime in the past, but my being not sure happened a little after my asking. So would it be more correct to say "I had asked you a question"? Just how much information is allowed to be assumed that they are happening around the same time?



I asked you a question, but you must have forgotten, since you still haven't gotten back to me.



Is it okay to use present perfect instead of simple past? I want to assume that my asking a question and her forgetting it happened around the same time, but it seems more natural to use present perfect here. Am I mistaken?


EDIT: I have additional questions:


I know this is kind of too late, but when I say "I asked you a question in my last email, but I wasn't sure (this is happening now) if you received it," don't I have to say "had received" in order to be correct? I think (write email -> try to send it -> be unsure if you received it) works here as well, but why do I have to use past perfect here?




Answer



The guiding principle should be don't use Past Perfect unless you really have to.


The uncertainty occurred after the asking - chronologically, and in the narrative sequence of OP's text. That's what normally happens when you report a series of events...



I did this. Then I did that.



It's grammatically possible, but completely pointless in most contexts, to express that as...



I had done this. Then I did that.






In OP's second example, it's pretty much impossible to avoid Present Perfect with the word must. You could get away with ...but it must be [that] you forgot..., but it's a bit "starchy". Present Perfect is perfectly natural here.


Consider, for example,...



1: You didn't answer the doorbell when I rang, so you must have gone to work early.
2: You didn't answer the doorbell when I rang, so you must have been in the shower.



Clearly in #1, the action in the present perfect clause (you going to work) happened before the simple past (I rang). But in #2, you being in the shower happened at the same time as I rang. That's not a problem in English; if the chronological relationship between actions is obvious from context, it doesn't always have to be made explicit by the verb forms.


2d - What is the pixels to units property in Unity sprites used for?


I'm starting to learn Unity for 2D development.


So, I am importing several sprites into the game, and I couldn't help but notice that there is a "pixels to units" property, by default on 100. I normally set it to 1. Is there a reason why I would need to have this value different than 1? Or, more generally, is there a reason to have multiple sprites with different




Answer



100 pixels per unit would mean a sprite that's 100 pixels would equal 1 unit in the scene. It's simply a scale to say how many pixels equal one unit. This can affect things like physics. A lower pixels to units setting would require more force to move one unit than a higher pixels to units setting.


Yes, there may be times where you'll want to manipulate the pixels per unit. If you have a tile sheet of 16x16 tiles, you may want to consider setting the pixels per unit to 16 so that you can easily snap tiles together in a scene, for example.


software engineering - What are the best resources on multi-threaded game or game engine design and development?


What are the best resources on multi-threaded game or game engine design and development? As this is obviously where computers are headed, I intend to study this topic and I'd like to know what resources and examples are out there.



Answer




Some intel resources.


http://software.intel.com/en-us/articles/designing-the-framework-of-a-parallel-game-engine/


http://software.intel.com/en-us/videos/dont-dread-threads-part-1/


Automated testing of games



Are there methods of automated testing of games?


Specific experiences are appreciated, with relevant information about the project such as platform and type of game if that helps with clarification.




A secretary with ____ good knowledge of English: "a" or no article?


I'm trying to pass a test on "Articles exercise" as they call it on the EnglishGrammar site. Reviewing my answers I got stuck about the two I posted on the picture below.


As I understand both words are uncountable (according to the Cambridge Dictionary), so it looks like (or said for example here in a guide to learning English from Frankfurt International School) I can't say a/an with an uncountable noun.


But this test says the opposite. Is there some trick? Or am I just dumb? Please help me to understand why I need to use "a" article in these cases?





  1. We need a secretary with ____ good knowledge of English.




    • a (marked as the correct answer)

    • the

    • a / the

    • no article is needed (the answer I think is correct)




  2. We're having ____ terrible weather.



    • a (marked as the correct answer)


    • the

    • a / the

    • no article is needed (the answer I think is correct)





Picture of the questions and answer



Answer



Unfortunately, I don't know if there's any solid rule you can use to explain why "a good knowledge of English" is correct. You are right that "knowledge" is an uncountable noun, but in this particular usage the idiomatic way to express it is with the "a". It's possible that the idiom distinguishes between "a knowledge of English" and other kinds of knowledge, or other degrees of knowledge, rather than just talking about the amount of knowledge.



Still, again, it's hard to pinpoint which nouns work like this, and which don't. Also, "knowledge" isn't the only uncountable noun where this applies:



I hear you have a good intuition about the future


I hope you have a clear understanding of what I mean.


They're trying to find someone with a good insight into the stock market.



It may be yet another case where you just have to memorize these exceptions as you come across them.


Anyway, as mentioned in the above comments, the given answer to the second question might be OK in some dialects, but "We're having terrible weather" is also correct.


quantifiers - Milk is countable or uncountable


I'm doing my homework. The question is



Is this sentence
Paul drinks much milk.
grammatically correct?




For me the answer is yes, because the quantifier "much" is used before non-count noun. But according my book my answer is wrong. Anybody can help me, please?



Answer



I think the lesson on Learn English Today is very clear.



A lot of can be used in all sentences: affirmative, negative and interrogative.
Much and many are used in negative and interrogative sentences.
They are rarely used in affirmative sentences, except if they begin the sentence.



So, the sentence in the question is most commonly written or spoken as: "Paul drinks a lot of milk."



The context seems informal, and using "much" in an affirmative gives a more formal tone that sounds odd when used for a simple statement like that one.


Here is an example of using "much" in an affirmative sentence from an article on theguardian.com: "There was much talk last week of how he would be remembered for keeping Britain out of the euro[...]"


It is common to use "much" in a negative, as in: "Paul doesn't drink much milk."


or in a question, like: "How much milk does Paul drink?"


"Much" is also used with too or so, as Damkerng T. points out: "Paul drinks too much milk." or "Paul drinks so much milk!"


Tuesday, May 24, 2016

game design - Why have the player pick up loot manually?



From a game-design perspective, I was wondering what the mechanic of manually picking up items off the ground does for the player. Keep in mind that items that fall on the ground can most likely be put into one of two groups:





  • Equipment Items: depending on the character the player is creating, the majority of these items might be ignored and left on the ground. Players will only pick up the ones that they want to "spend" inventory space and time (by clicking and eventually having to go back to town) on.




  • Consumables: gold, gems, crafting materials, etc - which players generally always want to pick up and sometimes don't take up inventory space.




While I can see that making players choose which items to pick up is an interesting "collecting" mechanic for the Equipment group, why make the "Consumable" group require manual picking up as well?





Examples of games which do this: (most diablo-esque dungeon crawlers)


Diablo 3


Path of Exile


Grim Dawn


Torchlight 2



Answer



Why are you giving the player loot in the first place?


It's a reward stimulus for the player. Games need a constant stream of reward stimulus (or at least the anticipation of a reward) to keep the player motivated to continue playing. The impact of a reward is not just determined by the mechanical effect (player now has 10 more gold to spend) but also by how much the player notices it.


By having the player interact with the reward in form of clicking to pick it up, you have the player notice it more which amplifies its psychological effect without changing its mechanical effect.


It also makes the player more aware of their current possessions. When you just put stuff into their inventory directly, they might easily miss that they just had the luck of finding the ultra-rare +99 sword of pwnage because they were focusing on something else. Then half an hour later they open their inventory for a completely different reason and wonder how they got it. The same applies to more generic resource-style items which the player collects in bulk. By getting a more direct feedback about the loot reward they get a clearer impression of which actions reward them with what kind of loot.



grammar - When can the determiner 'any' be omitted?


Can I omit any in the following sentence? If I do so, Do they sound natural and grammatical? 




  • Yesterday I had my camera with me, but I did not take any photos.


Many grammar books say it is not essential to use any. But I don't quite understand it. Can any teacher or expert please answer this?




unity - How to fade determine properties to fade materials out for the line renderer


I am trying to fade consistently fade a Line Renderer by adjusting the color property of it's material. I got the code I'm using from the accepted answer to How can I fade a game object in and out over a specified duration?. When I used the Default-Line material for the line renderer I got the following error:



Assertion failed: Material doesn't have a color property '_Color' UnityEngine.Material:get_color()



When I used the Default-Diffuse material, nothing happened.


Finally, when I used the Sprites-Default material it worked perfectly.


How can I make the line renderer fade out consistently based on different material?




c# - Spawning a Sphere and trying to move it




I've been trying to build upon a blog post on Gamasutra http://www.gamasutra.com/blogs/DarrelCusey/20130221/187128/Unity_Networking_Sample_Using_One_NetworkView.php In this I would like to spawn a sphere on the server and move it about and when it moves have the movement sent to the clients. On the GUI on the server I just want 3 buttons, spawn sphere, move left and move right. Ive been able to get the sphere to spawn fine, but when I press the button to have it move left or right nothing happens. Have I thought about this too simply? Where have I went wrong or what have I not included?


//***New Code***
if(GUILayout.Button ("Spawn sphere"))
{
Instantiate(spawnedSphere);
Debug.Log("sphere spawned");
}
if(GUILayout.Button ("Move Sphere Left"))
{
spawnedSphere.rigidbody.AddForce(new Vector3(-5000, 0, 0));

Debug.Log("Sphere went left");
}
if(GUILayout.Button ("Move Sphere Right"))
{
spawnedSphere.rigidbody.AddForce(new Vector3(5000, 0, 0));
Debug.Log("Sphere went right");
}

//***End New Code***

Answer




Replacing "Instaniate(spawnedSphere)" on line 3 with "spawnedSphere = GameObject.Instantiate(spawnedSphere) as GameObject;" fixed the problem.


After instantiating spawnedSphere, I didn't change its value. So I was trying to add force to the prefab.


articles - A cow is an animal vs The cow is an animal—which is correct and why?



After more than ten years of learning English, I still have a few problems with articles.
Which of the following two sentences is correct and why?



A cow is an animal.




or



The cow is an animal.





Monday, May 23, 2016

grammar - What Figure of Speech is used in phrases like "sugar mugar"?


There are combinations like sugar mugar that people use in their speech while the second word has no meaning and only adds a rhythm. What is this called in English?



Answer



In linguistics, this sort of repetition is called reduplication, and the second half is sometimes called a reduplicant. Reduplication is the most common term, but let's explore some more specific terms that are less common.


In your example, the reduplicant is altered, incorporating a special kind of prefix, and although there is no common term for this, a few linguists have called this a duplifix:



duplifix: an element attached to the base that consists of both copied segments and fixed segments (= a mixture of affix and reduplicant)


(Understanding Morphology, Haspelmath & Sims, p.326)




If we adopt this terminology, one common example would be the English duplifix (prefix) /ʃm/ (variously spelled shm or schm), and this process is sometimes called shm-reduplication. This particular duplifix is used to express a pejorative attitude toward the discourse topic – skepticism, dismissal, or similar sentiments:



Rene: What are you doing? You promised me breakfast.


Brodie: Breakfast, shmreakfast. Look at the score, for Christ's sake. It's only the second period and I'm up 12 to 2. Breakfasts come and go, Rene, but Hartford, "the Whale," they only beat Vancouver once, maybe twice in a lifetime.


(transcript from the movie Mall Rats)



Here, breakfast is the discourse topic, and Brodie is expressing a pejorative, dismissive attitude toward this topic with shm-reduplication.


More generally, this category of reduplication is also known as echo reduplication, and this occurs in many languages. In your example, mugar echoes sugar, but with the initial consonant replaced with /m/. This might be the best term for your particular example; it doesn't imply any sort of pejorative meaning like shm-reduplication does.


hardware - Do I really need to use a graphics API?


Is it necessary to use graphics APIs to get hardware acceleration in a 3D game? To what degree is it possible to free of dependencies to graphics-card APIs like OpenGL, DirectX, CUDA, OpenCL or whatever else?


Can I make my own graphics API or library for my game? Even if it's hard, is it theoretically possible for my 3D application to independently contact the graphics driver and render everything on the GPU?





pronunciation - How to pronounce decimals?


Something like:


0.1

0.23
0.999

How to pronounce them correctly in English?



Answer




0.1



"zero-point-one"




0.23



"zero-point-two-three"



0.999



"zero-point-nine-nine-nine"


"point" = the decimal point


python - How do you create a perfect maze with walls that are as thick as the other tiles?


http://journal.stuffwithstuff.com/2014/12/21/rooms-and-mazes/


I read this article about dungeon and maze generation. The author uses a kind of specialized algorithm for generating 'perfect' mazes that have walls of non-zero thickness.


(Edit: I misunderstood the term 'perfect' here. It actually means there are no loops in the maze)


As I understand, typical maze algorithms work for walls of zero thickness but this is not what I want.


He posted his code in the article, but after a cursory glance, I think I need someone to explain the procedure (or a similar one) in plain english.


My first two attempts looked like:


enter image description here


Which produces an effect with the diagonals that are unsightly.


and then:



enter image description here


Which is better but its not 'perfect' in the sense that it seems to waste some space.


If someone can give me simple english instructions I might post the python code after I get it working.



Answer



If I understand you correctly, you want to create a densely packed maze like this, where each wall is the same thickness as each corridor:


Maze with thick walls


But you say the maze algorithms you've found only deal with infinitely thin partitions between cells corridor cells, rather than thick walls like these.


Let's look closer. Here I've overlaid a grid on the maze above, colouring all the even columns blue, and all the even rows orange:


Maze with tinted rows & columns


You can see, the walls only show up on the coloured rows & columns. This gets a bit more obvious if we play with the grid spacing, making the coloured rows & columns thinner:



Maze with thinned rows & columns


Gosh, that looks a lot like the output of one of those algorithms with infinitely-thin maze walls, doesn't it? Just at half the resolution.


So, we can take any maze algorithm that works on a rectangular grid with infinitely thin partitions between cells, and convert it to a thick maze like so:



  • Open cell at (x, y) --> Open cell at (2x + 1, 2y + 1)

  • Wall between (x, y) and (x, y + 1) --> Wall cell at (2x + 1, 2(y + 1))

  • Wall between (x, y) and (x + 1, y) --> Wall cell at (2(x + 1), 2y + 1)

  • --> All corner cells (2x, 2y) are walls


Sunday, May 22, 2016

prepositions - What is the concept of the word 'Of'?


I think I really don't know well about the word 'Of'.




  1. The ball flew out of the window.




  2. The ball flew out the window.





Are those sentences the same?


Does the word 'Of' mean a thing like a criteria?


Please let me know the exact concept of the 'Of'.


Thank you so much.



Answer



You are asking for something which does not exist: prepositions do not possess "exact concepts" which can be recognized in every particular use. The "meaning" of a preposition depends on context—the particular words it joins—and is determined by historical contingency, not formal analysis of semantic content.


For any preposition it might be possible, with imagination and ingenuity, to work up a core "concept", a single definition which would embrace all the "meanings" the preposition is used to express.


But even if you had such a definition, it would be practically worthless. On the one hand the definition would be so vague that it would not help you understand what "meaning" the preposition was intended to express in any specific context. And on the other hand it would have so much overlap with the meanings of other prepositions that it would not help you predict which preposition you should employ in any given context.


You're not going to learn anything useful by looking for an "exact concept". What you have to learn is the constructions: the meaning expressed by the collocation of a preposition with specific words.


unity - get position of GameObject on rendertexture from camera


I'm rendering the camera output to an rendertexture on a plane. This works fine. But I want to put GameObjects on the rendertexture on positions of world objects that are visible on the camera.


camera.WorldToViewportPoint(obj.transform.position) shows the correct positions, but is not mapped to the rendertexture. How can I do this?


So it's GameObject in world > camera input > plane with RenderTexture > world or local position of gameobject on top of rendertexture plane.




Can anyone explain to me the subject and object in this sentence?


I was reading about pronouns and found this rule which I don't get at all.




The pronouns who, that, and which become singular or plural depending on the subject. If the subject is singular, use a singular verb. If it is plural, use a plural verb.


Example: He is the only one of those men who is always on time. The word who refers to one. Therefore, use the singular verb is.


Sometimes we must look more closely to find a verb's true subject:


Example: He is one of those men who are always on time. The word who refers to men. Therefore, use the plural verb are.


In sentences like this last example, many would mistakenly insist that one is the subject, requiring is always on time. But look at it this way: Of those men who are always on time, he is one.



I don't understand this at all. Isn't the subject "He"?



Answer



As the saying goes, a little knowledge is a dangerous thing. The writer of that piece of advice is badly informed.



To start, let's just look at these two versions of a possible sentence.





  1. He is one of those men who is always on time.




  2. He is one of those men who are always on time.






There are these two types of possible interpretation for the sentences:


A: He is one of those men. He is always on time.


B: He is one of those men. Those men are always on time.


Now it would be nice, wouldn't it, if sentence (1) always meant A, and sentence (2) always meant B. However, that's not the case. The fact is that native speakers, both in speech and writing, often use (1) to express B. The reason is that the word one often overrides normal verb agreement. In other words although sentence (2) definitely expresses B, sentence (1) would be used to express either A or B.


Here is what a vetted grammar source, based on real data, the Cambridge Grammar of the English Language has to say about this:



. . . The relativized element in these examples is object. Where it is the subject that is relativized, the expectation would be that the number of the verb would be determined by the antecedent, giving a plural verb in Type I, and a singular in Type II. In practice, however, singular verbs are often found as alternants of plurals in Type I:


[22]





  • i. He's [one of those people who always want to have the last word]. -- (Type I )




  • ii. He's [one of those people who always wants to have the last word]. -- (Type I )




  • iii. He's [one of her colleagues who is always ready to criticize her]. -- (Type II )





Examples [i] and [iii] follow the ordinary rules, but [ii] involves a singular override. It can presumably be attributed to the salience within the whole structure of one and to the influence of the Type II structure (it is in effect a blend between Types I and II ). But it cannot be regarded as a semantically motivated override: semantically the relative clause modifies people. This singular override is most common when the relative clause follows those or those + noun.



Now if you think about the following sentences carefully, you will see that the same thing applies:




  1. He is the only one of those men who is always on time.

  2. He is the only one of those men who are always on time.



C He is the one of those men. Only he is always on time.



D He is the only one of those men. They are always on time.


Sentence (3) could be used to mean either C or D. Sentence 4 can only be used for D.


In this kind of situation, thinking about the grammar is not the most useful guide. Even working out what the grammar is will take you quite some time. Go with your intuition!


References:


The Cambridge Grammar of the English Language, Huddleston & Pullum [et al], 2002.


Saturday, May 21, 2016

articles - With or without 'the' in "in (the) present participle form"?


Consider the two following extracts:



[...], which precedes the main verb in the present participle form, working.
The Teacher's Grammar of English with Answers: A Course Book and Reference Guide


If you use the verb dye in present participle form, the e must be retained to avoid confusion: dyeing.
Write in Style: A guide to good English


(Emphasis mine)



Both sources appear to be about good English. One is for teachers; the other is for good writing. One of them uses "the present participle form" (with the), whereas the other uses "present participle form" (without the).



Does the really matter at all in the extracts above? Is one of them more correct (or considered good usage) than the other? Or is it the case that both of them are correct but hint at different things?



Answer



He's in first grade and learning his ABCs.
He's in the first grade and learning his ABCs.


There is no meaningful (i.e. deliberately evoked and clearly perceived) difference. Both are acceptable and grammatical, and both could appear in the same idiolect in the same register.


Stages, forms, tiers, phases, grades, levels etc are perceived differently than spoons, cups, pencils, stones. The former can be projected as an isolated abstraction, or alternatively as belonging to an ordered sequence. When it's the latter, the definite article is used.


But...



OK Many of the passengers up in first class survived.


not OK Many of the passengers up in the first class survived.



OK Many students start thinking of college in junior year.


OK Many students start thinking of college in the junior year.



Unlike "first grade" and "the first grade", with "junior year" and "the junior year" there is a nuanced difference, one of register, the latter being the preference of bureaucrats. Someone who had gone only as far as elementary school could easily use both "in first grade" and "in the first grade", but someone who uses "in the junior year" is either a professional in the education biz or rubs elbows with such folks on a regular basis.


Difference between orthogonal map and isometric map


I am laughing at myself ignorant on this. Google didn't produce an obvious answer. Could someone explain what orthogonal map and isometric map are, and how they are different?



Answer



I made a picture to sum it up. Basically, the difference between both types of maps has mostly to do with the angle formed between each axis which results in one appearing to be seen from a topdown point of view, while the other appears to be seen from an angle:


enter image description here



It is also worth noticing the visual difference between an isometric projection and perspective projection which is what almost every 3D game uses.


enter image description here


Notice how lines are drawn parallel to each other when using an isometric projection, while when using a perspective projection, lines converge towards one (or more) vanishing points.


Does listening to English learning clips help to improve "Listening" skill?


I want to improve my listening skill in order to understand speaking of native English speakers. For this I have searched in the Internet and Youtube clips and finally figured out listening to English conversations, movies, clips etc might be very helpful for improving this skill.



So, I am here to ask a couple of questions related to this matter.




  • Does listening to same clips over and over again help or I should listen to new one once I am done with previous one?




  • How many times at least should I listen to audio files per day? (How long time should I spend per day?)



  • What should I do when I have stuck somewhere in the video (cannot parse what they are talking)? I should go ahead or I should not until understand all prior part of video



I have already noticed that this question might be off-topic because of its opinion-based nature, if this is so, please tell me the right Stack Exchange site which this question is on-topic at.


Note that my primarily focus is on American English not any other types of English.


Any answer would be highly appreciated, thanks in advance



Answer



My experience:



Does listening to same clips over and over again help or I should listen to new one once I am done with previous one?



As long as you understand a certain clip, move on. The more word patterns and vocalizations you learn, the better.




How many times at least should I listen to audio files per day? (How long time should I spend per day?)



As much as you can without getting discouraged.



What should I do when I have stuck somewhere in the video (cannot parse what they are talking)? I should go ahead or I should not until understand all prior part of video?



This is where some assistance might help.



1) Try to watch videos where the actions tend to follow what is being spoken. For example, an actor gets into a taxi and says "Take me to the airport and hurry". Even if you do not understand every word just by listening, the actions will help you grasp the correct word. After you hear and can recognize the same word a few times, it should stick in your memory.


2) Try to watch videos that have subtitles in the same language as the speech (not translations). But don't follow them unless you get stuck on a word.



3) Try to watch videos that have slow clear speech patterns. Try to stay away from heavy accents, fast or slurred speech etc. For music, slow, clear pronunciation (something like ballads as opposed to hard rock). Major network news programs are also good.



Friday, May 20, 2016

verbs - What is the difference between "wait" and "await"?


I'd like to know the difference between the two verbs since they seem to have the same meaning. When should I use await, and when wait?



Answer



Wait is an intransitive verb—it doesn't take a direct object; consequently it can't be cast into passive voice, and its past participle can't act as an adjective:




 We are waiting eagerly. but
We are waiting him.
The event is waited.
His eagerly waited arrival has been delayed.



Await is a transitive verb—it does take a direct object.



We await him eagerly.
The event is awaited.

His eagerly awaited arrival has been delayed.



Wait for may be treated as a transitive phrasal verb.



We are waiting for him.



But it is not ordinarily used in the passive voice. These are grammatically acceptable but sound a little odd.



? The event is waited for.
? His eagerly waited-for arrival has been delayed.




marks a usage as unacceptable ? marks a usage as questionably acceptable


prepositions - We see things ON / IN / AT the internet?



Which of the following prepositions is correct when talking about seeing something on internet?




You can see it ON / IN / AT the internet.




Answer



We usually use on with technical communication devices or programmes:



  • on the television

  • on the phone

  • on the radio

  • on the news

  • on the loudspeaker


  • on my walkman

  • on my stereosystem

  • on my ipod

  • on the internet


Hope this is helpful!


word choice - Usage of "to": can "to" here be replaced with "for"?



I have checked the usage of "to" in OALD. In the 18th definition, OALD gives an example:



It sounded like crying to me.



Can I use "for" instead of "to" here?



It sounded like crying for me.



If I can, do these two examples have any difference in meaning?


Can you please give me more examples? I'd like to get familiar with this usage.




Answer



If you use for in this expression it means something different.


"It sounded like X to me" means, roughly, that I interpreted what I was hearing it as X or I thought it sounded similar to X.



That statement sounds like a cover-up to me.
That bird-call sounds like a crow to me.



"It sounded like X for me" means (still roughly) that I expected what I was hearing to have X personal effect on me. In this particular case it would mean "I expected it to cause me to weep."



That policy sounds like higher taxes for me.

That demand from the client sounds like two or three weeks of round-the-clock work for us.



questions - what (color hair vs. hair color) do you have?


My hair color is black, and the question should be what is your hair color? or what hair color do you have?. However, it turns out surprisingly to me that the question with do is: what color hair do you have?, and if I were to ask about shoe size, I had to say: what size shoe do you wear?


Now I am confused because I am not sure if I am right asking about: some abc tool's shape, a pipe's length, some xyz solution's temperature and whatnot.


Are size and color exceptions, then, what tool shape do you make? or a rule, and so: what shape tool do you make?



Answer



If I was asking someone about the color of their hair, I might just say:




What is your hair color?



However, if I was forced to put the question in a "What ................. do you have?" format, I'd probably say:



What color hair do you have?



There is an exception (and that is the wonderful thing about English – it seems there's always an exception): If I was asking someone about hair coloring; that is, if I was talking about a product used to color hair (for example, if I'm asking about something like this):


enter image description here enter image description here


then I might ask instead:




What hair color do you have?



As for your tool question, think I would use something like:



What shape tool do you make?



although it's a rather awkward construct, and there's wiggle room for other wordings. In general, though, I think I prefer one of these formats:



What shoe size do you wear? or What size shoe do you wear?



What ice cream flavors do you sell? or What flavor ice creams do you sell?



Sometimes there are subtle nuances involved, like the way I changed flavors to flavor and ice cream to ice creams (that's because I'm expecting that the vendor will sell more than one flavor of ice cream). So, even though I could ask:



What size shoes do you wear?



I would probably not ask:



What shoe sizes do you wear?




unless I was expecting an answer like, "I wear Size 8 tennis shoes but Size 9 boots."


modal verbs - What is the difference between "might be" and "would be"?


To me both might and would appear to have similar meaning. E.g. consider the following sentences:.




  1. I think taking some rest after work would be good.

  2. I think taking some rest after work might be good.




The only difference I see is that would sounds more assuring than might. That is, in #1 speaker is more inclined to accept the fact that having some rest will be good, but in #2 speaker isn't sure about it. In #2 it is like 50/50, it can be good and it cannot be.


So, what is the difference between would and might?




Thursday, May 19, 2016

c++ - Loading and using an HLSL shader?


I've been looking everywhere and all I can find are tutorials on writing the shaders. None of them showed me how to incorporate them into my scene.


So essentially:


Given an hlsl shader, if I were to have a function called drawTexturedQuad() and I wanted the shader to be applied to the result, how exactly could I do this?


Thanks



Answer



There are three steps:




  1. Load effect and set the technique

  2. Provide data to the effect

  3. Render


1) Load effect and set the technique


  // Declaration of your effect variable
LPD3DXEFFECT mDSEGeometryStage;
...
initEffects()
{

//With this method you load your effect file
HR(**D3DXCreateEffectFromFile**( d3ddev, "./DeferredEffect_MaterialsStage.fx", 0, 0, D3DXSHADER_DEBUG, 0, &mDSEGeometryStage, &errors);)
// Some Error checking
if( errors )
{
MessageBoxA(0, (char *)errors->GetBufferPointer(), 0, 0);
errors->Release();
}
// Retrieve a Technique from your effects handler
D3DXHANDLE mhTech = mDSEGeometryStage->**GetTechniqueByName**("MaterialsTech");

// Set the technique to be used
HR(mDSEGeometryStage->SetTechnique(mhTech));
}

2) Provide data to the effect:


renderGeometryStage()
{
// Effect values handlers (String parameter is the name of a variable in your .fx file)
D3DXHANDLE mhView = mDSEGeometryStage->GetParameterByName(0, "gView");
D3DXHANDLE mhProjection = mDSEGeometryStage->GetParameterByName(0, "gProjection");

D3DXHANDLE mhNearClip = mDSEGeometryStage->GetParameterByName(0, "gNearClip");
D3DXHANDLE mhFarClip = mDSEGeometryStage->GetParameterByName(0, "gFarClip");

// Set effect values indicating the handler and the data as paramters
HR(mDSEGeometryStage->SetMatrix(mhProjection, &(camera->getProjectionMatrix())));
HR(mDSEGeometryStage->SetMatrix(mhView, &(camera->getViewMatrix())));
HR(mDSEGeometryStage->SetFloat(mhFarClip, camera->getFarClip()));

...


3) Render: As said in a previous answer



ID3DXEffect provides Begin() and BeginPass() methods.



So, in the same rendering method you can start to render by calling the device BeginScene() method and inside call the Begin or BeginPass methods of your effect.


    ...

// Begin Scene
HR(d3ddev->BeginScene());
{

...

// Clear targets surface
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET |D3DCLEAR_ZBUFFER,
D3DCOLOR_ARGB(0, 0,0,0), 1.0f, 0);

// Begin Effect passes.
UINT numPasses = 0;
HR(mDSEGeometryStage->Begin(&numPasses, 0))
{

// PLACE HERE YOUR RENDERING STUFF
// like: drawTexturedQuad();
}
// End Effect passes
HR(mDSEGeometryStage->End());
}
// End scene rendering
HR(d3ddev->EndScene());
}// End of renderGeometryStage method


Hope it helps, but your question is not about a chunk of code that you can copy/paste, its more about "basic" concepts. So for this kind of things I really recommend you to follow some tutorial because you will understand all the underlying concepts better. Cheers!


legalese - Is "murder" a noun or verb in "Mr Putin is guilty of conspiracy to murder"?


From The Telegraph's live feed on the ruling in the Litvinenko case:



Emmerson says report findings mean Mr Putin is guilty of conspiracy to murder and should be held to account.



Is this word murder a verb, like steal in "a desire to steal"? I mean, rephrasable to "conspiracy to murder someone"?


Or is it a noun, but with no article used because it's part of a set expression in legalese? I mean, could we rephrase it as "conspiracy to a murder" or "conspiracy to commit a murder"?



Answer



It is a verb. There's a simple test we can do, which is to see whether this word can take an Object. Verbs can take Objects, but nouns can't.


Sometimes nouns describe actions instead of things. These actions often have somebody who does the action and somebody or something that the action is done to. We normally show the person or thing that the action is done to using a preposition phrase headed by the preposition of. We can show the person or things doing the action with a preposition phrase headed by by. But we cannot try to give the noun an Object. This will be ungrammatical:




  • the release of the prisoners

  • the release of the prisoners by the government

  • *the release the prisoners (ungrammatical)


So let's see if we can find a phrase which includes the person or people being murdered:



  • The three men were convicted of conspiracy to murder people unknown.


Here we can see that the verb murder has a Direct Object, the noun phrase people unknown. Let's just check to see if maybe we could also use the noun murder here instead:




  • *The three men were convicted of conspiracy to murder of people unknown. (ungrammatical)


No, this result is very bad indeed. The word murder is definitely a verb here. This also means that the word to is part of an infinitival construction. It is not the preposition to which we see in go to the beach.


For most native speakers conspiracy to a murder would not be grammatical. However the noun conspiracy can take other infinitival clauses as Complements:



  • conspiracy to commit robbery

  • conspiracy to steal

  • conspiracy to injure



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