Monday, October 31, 2016

adverbs - Is this an adjective or a noun?



(1) Dotted here and there among the students, the ghosts shone misty silver.
(2) Then the hat twitched. A rip near the brim opened wide like a mouth - and the hat began to sing:
(Harry Potter and the Sorcerer's Stone)



Is the ‘misty silver’ a predicative adjective that denote the result of the intransitive verb like in the second example? Or is it an object of the transitive verb?




Answer



Oh, dear. This sort of thing is where ordinary part-of-speech and sentence-constituent analysis gets very iffy.


The actual meaning is perfectly clear:



The ghosts shone in such a manner that they looked misty silver.
The rip opened like a mouth. The opening was wide.



If you like to call the pair of adjectives misty silver (in which misty modifies silver) a secondary complement, that's cool; it gives you a name which tells you how it works.


But you can't do that with wide, because wide taken as an adjective wouldn't modify an entity present in the sentence, rip or mouth, but the implicit opening created. This is just how wide works. The simplest way of analyzing it is as an adverb on open; that's how OED treats it. It's very old in that sense, like hard, predating the practice of forming adverbs with the -ly suffix; and also like hard it has a doublet which does have the -ly suffix and which bears a slightly different meaning.


unity - How can I replicate Quantum Break's distortion particle effect?


Quantum Break has this fantastic particle effect, it's a distortion effect like broken glass. I want know how I can replicate this effect? You can see it below, and a full video is available on YouTube:


record_2018_02_05_16_34_26_307


record_2018_02_01_22_27_44_971



Answer





Unity default particle's shape is quad. first you need to change this shape to pyramid by using pyramid object or turns quads to pyramids with a geometry shader.


image


awd



To making broken glass effect(Refraction) you can use GrabPass { "TextureName" } that will grab screen contents into a texture.



GrabPass is a special pass type - it grabs the contents of the screen where the object is about to be drawn into a texture. This texture can be used in subsequent passes to do advanced image based effects.


https://docs.unity3d.com/Manual/SL-GrabPass.html



record_2018_02_03_23_09_06_370



Shader "Smkgames/GlassRefraction"
{
Properties{
_Refraction("Refraction",Float) = 0.05
_Alpha("Alpha",Range(0,1)) = 1
}
SubShader
{
Tags {"Queue"="Transparent" "RenderType"="Transparent"}


Blend SrcAlpha OneMinusSrcAlpha

GrabPass
{
"_GrabTexture"
}

Pass
{
CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
};


struct v2f
{
float4 grabPos : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float _Alpha,_Refraction;

v2f vert (appdata v)
{

v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.grabPos = ComputeGrabScreenPos(o.vertex);
return o;
}

sampler2D _GrabTexture;

fixed4 frag (v2f i) : SV_Target
{

fixed4 col = tex2Dproj(_GrabTexture, i.grabPos+_Refraction);
return float4(col.rgb,_Alpha);

}
ENDCG
}
}
}



Let’s proceed with a shader that displays mesh normals in world space. I used it because I wanted to look three dimensional broken shape.


normals


record_2018_02_05_18_06_09_41


record_2018_02_03_23_19_06_705


    Shader "Smkgames/BrokenGlass3D"
{
Properties{
_MainTex("MainTex",2D) = "white"{}
_Alpha("Alpha",Float) = 1
}

SubShader
{
Tags {"Queue"="Transparent" "RenderType"="Transparent"}
Blend SrcAlpha OneMinusSrcAlpha


GrabPass
{
"_GrabTexture"
}


Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata

{
float4 vertex : POSITION;
float2 grabPos : TEXCOORD0;
float3 normal :NORMAL;
};

struct v2f
{
float4 grabPos : TEXCOORD0;
float4 vertex : SV_POSITION;

half3 worldNormal :TEXCOORD1;

};
sampler2D _MainTex;
float _Intensity,_Alpha;

v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);

o.grabPos = ComputeGrabScreenPos(o.vertex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
return o;
}

sampler2D _GrabTexture;

fixed4 frag (v2f i) : SV_Target
{
fixed4 c = 0;

c.rgb = i.worldNormal*0.5+0.5;
float4 distortion = tex2D(_MainTex,i.grabPos)+_Intensity;
fixed4 col = tex2Dproj(_GrabTexture, i.grabPos+c.r);
return float4(col.rgb,_Alpha);
}
ENDCG
}
}
}



To creating heat distortion you can use flow map



A flow-map is a texture that stores 2d directional information in a texture. The color of the pixel determines what direction it is using the uv-coordinates texture as a base. The more color there is the faster the proportional speed. Example green tells it to go up-left, the center is neutral, and red will go down right. It’s a useful technique for liquid materials like water, and a useful alternative to just a panner node.



flow_map


heatdistortion


    Shader "Smkgames/HeatDistortion"
{
Properties{

_DistortionMap("DistortionMap",2D) = "white"{}
_Intensity("Intensity",Float) = 50
_Mask("Mask",2D) = "white"{}
_Alpha("Alpha",Range(0,1)) = 1
}
SubShader
{
Tags {"Queue"="Transparent" "RenderType"="Transparent"}

GrabPass

{
"_GrabTexture"
}

Blend SrcAlpha OneMinusSrcAlpha

Pass
{
CGPROGRAM
#pragma vertex vert

#pragma fragment frag

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
};

struct v2f

{
float4 grabPos : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _Mask,_DistortionMap;
float _Alpha,_Refraction;

v2f vert (appdata v)
{
v2f o;

o.vertex = UnityObjectToClipPos(v.vertex);
o.grabPos = ComputeGrabScreenPos(o.vertex);
return o;
}

sampler2D _GrabTexture;
float _Intensity;

fixed4 frag (v2f i) : SV_Target
{

float mask = tex2D(_Mask,i.grabPos);
mask = step(mask,0.5);
//mask = smoothstep(mask,0,0.4);
float4 distortion = tex2D(_DistortionMap,i.grabPos+_Time.y)+_Intensity;
fixed4 col = tex2Dproj(_GrabTexture, i.grabPos*distortion);
return float4(col.rgb,mask*_Alpha);

}
ENDCG
}

}
}

another example by using normal:


cutout


normalmap


smoketile_normal 1


Shader "Smkgames/HeatDistortion2" {
Properties {
_CutOut ("CutOut (A)", 2D) = "black" {}

_BumpMap ("Normalmap", 2D) = "bump" {}
_BumpAmt ("Distortion", Float) = 10
}

Category {

Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Opaque" }
Blend SrcAlpha OneMinusSrcAlpha
Cull Off
Lighting Off

ZWrite Off
Fog { Mode Off}

SubShader {
GrabPass {
"_GrabTexture"
}
Pass {

CGPROGRAM

#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#pragma multi_compile_particles
#include "UnityCG.cginc"

struct appdata_t {
float4 vertex : POSITION;
float2 texcoord: TEXCOORD0;
};


struct v2f {
float4 vertex : POSITION;
float4 uvgrab : TEXCOORD0;
float2 uvbump : TEXCOORD1;
float2 uvcutout : TEXCOORD2;
};

sampler2D _BumpMap,_CutOut,_GrabTexture;
float _BumpAmt;

float4 _GrabTexture_TexelSize;
float4 _BumpMap_ST,_CutOut_ST;

v2f vert (appdata_t v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y*-1) + o.vertex.w) * 0.5;
o.uvgrab.zw = o.vertex.zw;
o.uvbump = TRANSFORM_TEX( v.texcoord, _BumpMap );

o.uvcutout = TRANSFORM_TEX( v.texcoord, _CutOut );
return o;
}



half4 frag( v2f i ) : COLOR
{
half2 bump = UnpackNormal(tex2D( _BumpMap, i.uvbump )).rg;
float2 offset = bump * _BumpAmt * _GrabTexture_TexelSize.xy;

i.uvgrab.xy = offset * i.uvgrab.z + i.uvgrab.xy;

half4 col = tex2Dproj( _GrabTexture, UNITY_PROJ_COORD(i.uvgrab));
fixed4 cut = tex2D(_CutOut, i.uvcutout);
fixed4 emission = col;
emission.a = (cut.a);
return emission;
}
ENDCG
}

}

}
}


If you pay attention to your first gif you can see little RGB split.


u_rgb_seperation_ar


Shader "Hidden/RgbSplit"
{

Properties
{
_MainTex ("Texture", 2D) = "white" {}
_NoiseTex1 ("Noise Texture A", 2D) = "white" {}
_NoiseTex2 ("Noise Texture B", 2D) = "white" {}
}
SubShader
{

Pass

{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;

float2 uv : TEXCOORD0;
};

struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};

v2f vert (appdata v)

{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}

sampler2D _MainTex,_NoiseTex1,_NoiseTex2;
float3 colorSplit(float2 uv, float2 s)
{

float3 color;
color.r = tex2D(_MainTex, uv - s).r;
color.g = tex2D(_MainTex, uv ).g;
color.b = tex2D(_MainTex, uv + s).b;
return color;
}

float2 interlace(float2 uv, float s)
{
uv.x += s * (4.0 * frac((uv.y) / 2.0) - 1.0);

return uv;
}

fixed4 frag (v2f i) : SV_Target
{

float t = _Time.y;

float s = tex2D(_NoiseTex1, float2(t * 0.2, 0.5)).r;


i.uv = interlace(i.uv, s * 0.005);
float r = tex2D(_NoiseTex2, float2(t, 0.0)).x;

float3 color = colorSplit(i.uv, float2(s * 0.02, 0.0));

return float4(color, 1.0);

}
ENDCG
}

}
}


https://www.fxguide.com/featured/time-for-destruction-the-tech-of-quantum-break/


Source On Github


2d - How do I find the intersection of two lines



I have a bounding box on my character, its position in the previous frame an the current frame. The bounding box is axis aligned.


My character is running around inside a cave, I have a list of points (lines) that represents the wall of the cave (not axis aligned)


I've got a coarse grained algorithm that tells me when some part of my character is likely to have collided with some part of the cave wall.


I do not have a fine grained algorithm to tell me specifically which line of the wall was collided with and at which point.


My current thought was that I could just create a line for each corner of the bounding box from its position in the previous frame, to its position in the current frame, then test each of these lines for intersections with any of the lines in the cave wall.


My google fu however hasn't shown me an easy formula for calculating intersections. Have I picked a bad way to do this, or am I just bad at search?


My game is written in scala, however I can read/translate most any c style language and many scripting languages, whatever you feel like answering in



Answer



googling " intersection test line segment line segment" produced this:


http://paulbourke.net/geometry/lineline2d/



spelling - Words to Disambiguate Alphabet Letters from Others


Dictating e-mail/website addresses each one letter by one on a phone call is always challenging for me. I found that listeners often misspell certain letters like B/D/V because the pronunciation is distorted.



With a list of 26 words that represent each alphabet letter, if any, communications are going to be easier:



I: R-A-N-D-O-M-A-L-P-H-B-E-T.


Listener: (Simultaneously) R-A-N-D-O-M-A-L-P-H... wait. D or B?


I: It's B. B of 'black'.



'Black' is a quick example of my own but seems good enough because 'black' is simple, easy, and there's no word such as "vlack", "dlack", "glack", etc.


I'd love the list of words like 'black' if there is already one in common use.



Answer



What you are describing is called a phonetic alphabet.



There are a number of common phonetic alphabets used in the English language.


One of the most popular ones is the International Civil Aviation Organization (ICAO) alphabet, commonly called the NATO phonetic alphabet. See https://wikipedia.org/wiki/NATO_phonetic_alphabet for a complete reference.


word choice - 'Golden spoon' or 'Gold spoon' -if the spoon is made of gold?


Adjective or noun?



A golden spoon or A gold spoon




What to use? A spoon is made of gold.


enter image description here


Dictionary says:



golden (adjective) -made of gold



But then... (the same page)



golden (adjective) - bright yellow in colour like gold




So, what should we prefer while referring to a spoon made of gold?




opengl - How to subdivide a quad?


I'm working with OpenGL and I'm importing from a file coordinates for quads in the following format:


 0.0 1.0 0.0 //normal vector
20.0 -5.0 20.0 10.0 10.0 //x y z u v
20.0 -5.0 -20.0 10.0 0.0
-20.0 -5.0 -20.0 0.0 0.0

-20.0 -5.0 20.0 0.0 10.0

I want to tessellate the quad so I'm starting with this:


------------
| |
| |
| |
------------

And I should get this:



-------------
|___|___|___|
|___|___|___|
| | | |
-------------

Can you guys help me creating the subdivide function? I'm struggling with it...



Answer



To subdivide your quad in n*n sub-quads, you create n*n sub-quads inside it. There are several ways of doing this, so there is not such thing as the subdivide function.


Things get messy if you want to handle the most general case, i.e. a quad that is not necessarily a perfect square. Your illustration does not really tell us what you want. There is a whole lot of different kinds of quads (and this is only for "proper" quads, lying on a plane).



So I'm giving you one solution for gentle quads that are not too weird (so, convex quads), but don't expect it to work in every case. You can create line segments that start and end at regular intervals on each of your original quad's edges, and use these as edges for your new quads. E.g. with n=3:


Naive subdivide


In pseudo-code:


function naiveSubdivide(quad, n)
assert that n > 0
for i from 0 to n-1
// the P1-P2 line segment
P1 = A + i * (D - A) / 3
P2 = B + i * (C - B) / 3
// its sibling to the "right", Q1-Q2

Q1 = A + (i + 1) * (D - A) / 3
Q2 = B + (i + 1) * (C - B) / 3
// create n sub quads along the line segments
for j from 0 to n-1
A' = P1 + j * (P2 - P1) / 3
B' = P1 + (j + 1) * (P2 - P1) / 3
C' = Q1 + (j + 1) * (Q2 - Q1) / 3
D' = Q1 + j * (Q2 - Q1) / 3
create a new quad with vertices A', B', C' and D'
end for

end for
end function

For the general case, it's probably possible to write an entire book about it, but my guess is that working with triangles instead of quads would already be a good start.


word choice - Should I say "She is in the park" or "She is at the park"?


I am really confused. Which preposition is correct?



She is in/at the park.
They are in/at the park.
I am in/at the park.




Should I use in or at in these sentences?




Sunday, October 30, 2016

questions - Can I ask 'what your name is?'


Can I ask:




  1. 'What your name is?'



instead of,





  1. 'What is your name?'



Is #1 grammatically correct?




xna - Fighting Game and input buffering


In fighting game, there is an important thing called input buffering. When your character is doing an action, you can input the next action that will activate as soon as possible (the buffer is 5-10 frames).



Has anyone already implemented, or knows the most efficient way to do this?


I thought of things like this:


Enum list moves (a list of all my moves)
if (moves = fireball)
{
if (Mycharacterisidle)
{
Do the fireball
}
else if (MycharacterisMoving)

{
if (lastspriteisnotfinished)
{
InputBuffer++;
}
else if(spriteisfinished && InputBuffer < 5)
{
Do the fireball
}
}

}

Any better ideas? Thx.




Saturday, October 29, 2016

grammar - "industry" or "industrial"



From VOA Special English:



Growers get industry news along with advice and information from experts.



Why is it "industry" instead of "industrial"? I know that "news" is a noun, and generally in front of a noun is an adjective. But "industry" is just a noun, too. So I think "industrial" may be more agreeable. Can someone tell me why does it use "industry"? Thanks!



Answer



In English, nouns combine together to form noun phrases. The syntax of a noun phrase is a lopsided tree, headed by the rightmost noun, for instance:



law school admission test




This string of nouns denotes a thing which is a kind of test. More specifically, an admission test: a test to determine suitability for admission. More specifically, a school entrance test: a test to determine suitability of admission to a school. And so on.


Almost all nouns can combine together to make noun phrases, even proper nouns:



Did you attend the Paris convention? [Did you attend that convention which was in Paris?]


That's a real Jennifer thing to do! [Jennifer's action is typical of Jennifer's usual behavior.]



The string of nouns only has to make sense, and sense can be established by context. For instance there is no such thing as a "table door", but if you somehow introduce something like that to your audience, they will accept it; in any case, it is not ungrammatical.


It is also important to note that certain combinations of words have entrenched meanings, and it makes a difference whether you use the adjectival form or the noun.


In this particular case, "industry news" is in fact much more correct than "industrial news". The reason is that it is news about the industry: writing produced by industry pundits (who, also, are not "industrial pundits").


Something "industrial" is of the industry: something used or produced by the industry.



A machine, tool, or part can be industrial:



Our company produces {industrial | industry*} robots.


{Industrial | Industry*} versions of microchips can withstand wider temperature ranges than consumer versions.


My brother-in-law studied {industrial | industry*} engineering, became an {industrial | industry} expert, but ended up working as an {industry | industrial*} journalist.


A truck full of {industry | industrial*} materials overturned on Highway 37, southbound just before exit 53.



Although both "industrial expert" and "industry expert" are used, but they are not necessarily the same thing. My intuition is that an industrial expert might be someone who has knowledge about the processes and materials within some industry (an expert in matters industrial), whereas an industry expert is someone with a broader outlook on an industry as a whole, including perhaps the business side of things (expert in matters concerning the industry).


How to implement level transitioning for 2D Platformer (tile-based)


I'm making a 2D tile-based platformer in C++/SDL and I want the player to move to the next level when they run off the side of the level, but I'm not sure how to implement this. I have tried putting colliders on the tiles at the edge of the map but it seems like there could be a better than than designating special tiles.


I wasn't sure what to keywords to search for when looking for a solution so if you can point me to a useful guide that would be great!


I'm looking for something very similar to how Super Metroid handles level changing.




scale - What makes scaling pixel art different than other images?


Recently I was coaching a developer who's new to making pixel art games, and realized there's some "conventional wisdom" around scaling pixel art that's not obvious to a newcomer, and might not be well documented. So, here's an attempt to fix that....






  1. I've heard I should only scale pixel art by 200%, 300% etc. not in-between sizes like 120%




    • Why is that? Shouldn't scaling "just work" the way it does with other images?

    • What if I really need to make my character just a fraction larger or smaller to get the right gameplay or look? How do I fix this?




  2. I'm told it's "bad" to use pixel art at different scales in one game - why?



    • For example, if I scaled up my character so each sprite texel is 4x4 screen pixels, while my background art is scaled up so each sprite texel is 6x6 screen pixels. Isn't a pixel a pixel at the end of the day?






Answer



Scaling by Whole Numbers


Scaling by 2x, 3x...nx is simple - each pixel just becomes an nxn square of pixels, and the look of the original sprite is perfectly preserved (including all the sharp lines, corners, and staircase zig-zags).


We run into trouble though when scaling pixel art by a fractional amounts (eg. 1.5x) because pixels are discrete by nature. We can't really have "half a pixel."


For other kinds of art we can often get away with blending adjacent source pixels where the pixel should be "half coloured," and at high resolutions the artifacts usually aren't noticeable. But on big chunky pixel art this quickly destroys the crisp look.


So instead we'll usually use "Nearest Neighbour" filtering (also called Point filtering) so that each pixel after scaling takes its colour from exactly one pixel in the original sprite.


This has another wrinkle: since the number of pixels after scaling isn't a whole-number multiple of the number of source pixels, some source pixels will get duplicated more than others (if scaling up) or skipped entirely (if scaling down).


Unfortunately, image editing software and GPU texture filtering aren't very choosy about where they duplicate or skip pixels - they just follow basic rounding rules - which can make the result look distorted and uneven.


Check out the example below. In the middle we've scaled up the mushroom sprite by 150% using Nearest Neighbour filtering, and the result looks wonky and haphazard. One eye is bigger than the other, some outlines are thick while others stay thin, and the rounded spots look blocky... it doesn't look like something a pixel artist would draw on purpose.



Example of artifacts from using a non-integer scale


If we really need the sprite to be 150% bigger (say, to make the gameplay feel right, or to support alternate display resolutions), then we can repaint the problem areas like the example on the right. Now it looks more like something an artist would make, and stylistically consistent with other art in the game. (Though I'm not a great pixel artist myself, so it could still be better 😉)


Unfortunately there aren't a lot of great shortcuts for this. For whole-number scales, you can use specially-designed pixel art upscaling algorithms - a wide variety are available in tools like ImageResizer - to get a less blocky starting point than Nearest Neighbour, but it still takes an artist's eye and some elbow grease to get a high-quality result.




Aside: fractional scales can also crop up at runtime.


Imagine your game is in NES resolution (256 x 240), and you want to display it on a 1080p screen.


1080 ÷ 240 = 4.5, so some of the source pixels or "texels" in your scene get blown up to 5 screen pixels across, while others are only 4, creating distortions like we saw above. In motion they tend to make sprites ripple and shimmer distractingly, without an obvious cause:


Example of a fractional-scaled mushroom moving, showing rippling artifacts


You'll often see people suggest rounding camera or object positions to integer pixel coordinates, but that doesn't really fix the problem. Rounding already happens as part of the nearest neighbour filtering - the problem is that some screen pixels round to the same source texel (duplicating it), while others don't, leading to an uneven result.


The solution is to use a combination of padding/cropping or alternate asset sets to get back to a consistent, whole number ratio of screen pixels to texels for each display resolution you want to support - see some Unity examples here. This is another case where there's no easy universal fix, and you'll have to apply some judgement and artistry to keep your game looking sharp.



Keeping Pixel Scale Consistent


This "rule" comes down to stylistic consistency.


When you use pixel art at different scales, it can look like assets have been cobbled together from different games, instead having a unified aesthetic.


Example of scaling assets differently in a single game


In the example on the left, I put together some sprites from Super Mario World, all at the same scale, and it looks great.


In the middle, I scaled up Mario and the level to twice the resolution of the background, and the mole to triple the resolution. Since I used whole-number scales, we don't get distortions or ripples anywhere, but it still looks a little funny.


For one, the background is so much more detailed than the foreground. It's able to represent smooth curves and sharp highlights, which makes the foreground look particularly "blocky" in contrast, rather than having a consistent pixel art feel. And the mole's outlines are noticeably thicker and more jagged than the rest of the foreground.


At the right I show that again, by repainting the assets in a common pixel scale, we can bring back a more unified and intentional feel with the new asset sizes.


But Do I Have To?


No, not really. It's your game, and you can make it the way you want.



Especially when prototyping and finding the fun in your game, being able to try stuff fast is more important than having it look perfect. You'll probably get the size of important things like your character wrong many times before you find what's best for your game, and it would suck to have to repaint every animation frame each time you want to try something different. So, early on, don't sweat it.


For the released game, it's a judgement call. No pixel art police will ban you from distributing your game if you don't follow the rules, and many players wouldn't be able to describe the difference. But attention to these pixel details is something many players (and reviewers) consider an important sign of quality - so get to know your audience, and decide what's best for the experience you want to offer them.


One last consideration is that a lot of pixel art games have very high-precision gameplay. Think of hopping between 1-block platforms in the early Mega Man games. In these situations, a consistent pixel grid (and tile grid) can be an important cue for the player in judging and executing their moves. Introducing irregularity in the art might actually make the game harder to learn, which can be frustrating.


prepositions - "be accorded someone" or "be accorded to someone"?


When the verb accord means "give or grant", should the passive voice be accorded someone or accorded to someone?


I came across several sentences in a book:



The attention accorded husband-wife relations in Muslim teachings thus confirmed the indigenous view of matrimony as a desirable state, with the birth of children considered essential for the full attainment of adulthood.



Similar processes occurred in Daoism, which percolated into Vietnam from southern China but never received the official patronage accorded Confucianism.



Shouldn't it be "accorded to husband-wife relations", as "given to husband-wife relations"?




2d - Can I jump from A to B?


I'm making some rudimentary AI for my side-scroller and I need to know whether an AI unit can reach point B from point A simply by taking a jump.


Flight trajectory of my characters is a bit unusal as they can apply force in mid-air (like in Jazz Jackrabbit 2 for example), so unlike the classic trajectory of a projectile which is about...



path that a thrown or launched projectile will take (...) without propulsion.




... I suppose that my problem is more about a projectile with propulsion (e.g. rocket).


To illustrate this, this is how the flight curve looks like for my character if I jump and continually press the "left button" (it looks different at the left end, this is where I was making some manuevers in mid-air): enter image description here


The force applied during flight is always parallel to the X axis, so it is F = (-f, 0) if I hold "left" and it is F = (f, 0) if I hold "right".


He can move very much like a ski jumper:


enter image description here


So it differs a lot from the classic trajectory which is simply a parabola (source: wikipedia):


enter image description here


To make it more difficult, I am simulating simple air resistance so my characters can accelerate only up to some maximum speed value.


This is done by applying a small force in the opposite direction of travel:


b2Vec2 vel = body->GetLinearVelocity();

float speed = vel.Normalize(); //normalizes vector and returns length
body->ApplyForce( AIR_RESISTANCE_MULT * speed * speed * -vel, body->GetWorldCenter() );

The AIR_RESISTANCE_MULT is a constant that in my case equals 0.1.


Let's assume that my character is an infinitely small point.


And I'm NOT taking obstructions into consideration, so my question goes like this...


How to determine (at least reliably guess), given initial velocity V, an impulse J = (0, -j) that I apply to the character upon jump, gravity G = (0, g), force F = (+-f, 0) continually applied during flight and AIR_RESISTANCE_MULT if we really decide to take air resistance into account (this is optional) , whether a point lies below the curve drawn by the path my character will take?


I have literally no idea where to start with the calculations and in fact, I am not necessarily interested in an exact answer; a well working hack/approximation would be great as the AI by no means needs to act perfectly.


edit: I've decided to solve this using simulation as Jason suggests, but how to handle such a case? enter image description here


Should I draw a segment from C to D and check whether the desired point lies below this segment?



Or should I binary search the timesteps between C and D to look for the point that is close enough in horizontal distance to the desired point, and only then check the vertical difference? (seems a bit overkill to me)



Answer



As you state, the best choice is to approximate, in this case using a numerical scheme. Divide time into large timesteps (say 100-300ms), and use the parabolic approximation for each timestep. The forces are the same throughout except air resistance. The parabolic path is basically for constant acceleration, but with air resistance the acceleration changes because the force depends on speed. A reasonable approximation is to treat air resistance as constant over each timestep. But using a quadratic (i.e. parabolic) approximation when integrating allows you to handle much larger timesteps. Then you just compute until a parabola crosses the desired point in the horizontal direction, and then compare the heights.


EDIT: A little more detail about the comparison. You know that over the timestep (which could be many in game frames), that the player crosses the target . Their path is described by the position where:


ax = 1/2 * accel.x
bx = velocity.x
cx = position.x

t is the time through the timestep (0 <= t <= dt) and similarly for y. So when t=0 the character is at the previous position, and when t=dt, they are at the next position. Note that this is basically the Euler update with dt replaced by t so that we can calculate anywhere along the trajectory. Now we know the x-position is a quadratic function, so we can solve ax*t^2 + bx*t + cx = targetx and get (up to) two times during the step in which the character is directly above or below the target. Then we throw out any solutions that aren't in the range [0, dt], as these aren't in the current timestep. (For robustness, add a small constant to the ends of the range so you don't have round off problems). Now we could have no solutions (after filtering), in which case we don't hit the target this timestep. Otherwise, we evaluate ay*t^2 + by*t + cy at the solutions, and compare this y with targety. Note that you could be above the target at one point in your trajectory, and below it later (or vice-versa). You'll need to interpret such situations according to what you want to do.


Considering a bunch of timesteps is much easier than finding an analytic solution to the original problem, and far more flexible as you can change the motion model and this will still roughly work.



Bonus points for using variable steps, for example, 100ms for the first second (ten points), 200ms for the next two (ten more points), 400ms over 4 seconds, etc. In fact, as your character approaches terminal velocity the variation in the resistance goes down, and you don't need larger timesteps anyway. This way you can handle really long jumps without too much processing, as the complexity for T seconds is O(log T) rather than O(T).


You can also simulate what happens when the character stops boosting partway through their jump, or starts boosting the other way. With the above trick the complexity is O((log T)^2), which isn't too bad.


game design - What are the reasons for MMOs to have level caps?


In many MMOs players character progression is artificially capped, e.g. by level 60 or 90 or 100 or whatever. Why do MMOs have these level caps in the first place? Why not just allow characters to continue to arbitrary levels with a mathematically designed leveling system that keeps the leveling experience interesting and endless?


Answers to this question may help us to see the reason behind the feature and decide if and how this should be implemented in our MMOs.




Answer



This is not a problem specifically related to MMOs; single-player games often have level caps as well, and the fundamental reason for introducing them is the same.


It's much easier and more practical to balance for a fixed range of progression than an infinite one.


You postulate that one could just implement a "mathematically designed leveling system that keeps the leveling experience interesting and endless" but this is much harder to do than it is to say (assuming you still want "fun"). Essentially all this is doing is finding power curve that isn't too shallow or too steep and using that curve to scale a player's statistics.


This is not likely to remain interesting for a long time. It lacks variety. It's just numbers getting increasingly bigger, and while that may entertain a few people for a little while you will eventually reach the point where the numbers are too big to be effectively comprehensible (42,132,927,189,100 strength) and don't have an appreciable impact (you might deal 92,101,626,001,292 damage per second at level 67,192 but enemies your level have a similarly inflated HP score, so it still takes you the same amount of time to actually kill them as a level 67 player).


Players are usually engaged by progression that introduces variety and choice (for example in the array of abilities they can chose from). A secondary effect in the introduction of choice is the ability to plan, to elect abilities or skills or gear that synergizes with itself in a particular way. While many games end up with some of those synergies organically, at least a good portion of them are initially planned for; it's much harder to ensure that sort of opportunity for fun exists in a system where abilities are randomly-generated and made available.


A system with procedurally-generated progression breakpoints is totally possible. It's hard to tune into something fun, though, because the more procedural variety you introduce the less designer control for fine-tuning you have. This means the designer is often forced to balance against the potential components of an ability set, not the abilities themselves. For a concrete example of such a thing in a small (non-infinite scale), consider the original Guild Wars and its expansion chapters. Each chapter introduced a large new set of skills, and player progression was mainly measured in skills and not level (which was capped at 20). Balancing for that combinatorial explosion was extremely difficult and allowed several undesirable, unbalanced (both over and under powered) combinations at times. That's why Guild Wars 2 chose to go with a much more directed and focused system.


A fully-procedural progression breakpoint system would be interesting, but nobody's tried/done it well yet -- and besides, assuming a perfect implementation of such a thing, you wouldn't necessarily need levels at all at that point.




There is a related discussion, and that is about capping lower than you eventually expect to allow (for example, how Diablo 3 initially capped you at 60, and GW2 at 80). This allows you to still design for a fixed range of progression but also expand that range somewhat -- offering new rewards and other such carrots -- to players who purchase expansions at a later day. WoW also does this, of course, but like the above it is not strictly anything to do with MMOs.



Go down the hall meaning? (For giving directions)


When I asked for the directions to the HR's cubicle, I got this reply:



Go down the hall then take the first left, You will find the HR's cubicle there.




(I don't remember exactly what he said.)


I am assuming by down the hall he meant to go straight and then take a left.


Can I apply the same logic for streets and roads while giving the directions?


Go down the road and then take a left.


I would really appreciate if someone can explain the meaning of the phrase "down the hall" in this context.




prepositions - "Conjure" vs "conjure up"


What's the difference between the two? Example:


I conjured a random number.


I conjured up a random number.



Answer



By itself, conjure means to cause something to appear by magic (literally), especially by a magic incantation. For example, "Faustus conjured a demon."


Conjure up can mean the same thing, but more often suggests that you're using conjure metaphorically to describe producing something in a more prosaic way, like inventing or improvising or randomly choosing something. It also suggests producing it quickly and unmethodically.


This works by analogy with many other phrasal verbs where up is added to some weightier verb to "lighten" its meaning and/or suggest producing something immediately or carelessly, like these:





  • whip / whip up (whipping cream is a laborious activity; "whipping something up" suggests making something, like something to eat, quickly using whatever ingredients happen to be available, with little effort)




  • make / make up (to make something is to produce it, usually suggesting skill or deliberation; to "make something up" is to invent or improvise something purely from imagination, suggesting very little deliberation and/or no basis in fact)




  • turn / turn up ("whatever turns up" means whatever arrives, without much planning or control)




  • show / show up (to "show" something is to demonstrate it, usually to an attentive audience; to "show up" is merely to appear, as in "Let's see who shows up at school today")





  • meet / meet up (both mean the same thing, but the latter is less formal, suggesting meeting unexpectedly or meeting briefly)




I take the up in these phrasal verbs to suggest lightly flicking one's hand upward, tossing things into the air in front of you, letting them assemble into whatever they happen to make—or else something appearing just now, coming "up" into your field of vision.


(Of course up builds phrasal verbs in other ways, too.)


verbs - Active construction of 'Our team is so blessed...'?


Would anybody specify the active form of the following passive sentence.



Our team is so blessed to have each other




Also please let me know the significance of "have" in the above sentence.


I really appreciate any help you can provide



Answer



In your sentence, 'blessed' has the idea of 'fortunate. 'Our team is blessed' is not really a passive construction.


If you are deeply religious, you may feel that it is passive, suggesting "God has blessed our team", but you then need to change the rest of the sentence to something like "in giving us each other".


Friday, October 28, 2016

verb forms - "Split along idealogical lines" meaning




When the court deals with social policy decisions, the law it shapes is inescapably political-which is why decisions split along ideological lines are so easily dismissed as unjust.



I have a few questions about this sentence:



1) Why does it read split along and not splitted along? Could it have been either?


2) What does split along ideological lines mean?


3) What does dismiss mean in this context, and how should I interpret the whole sentence?



My present comprehension of dismiss is that it means reject or turn down.


But the problem is the word decisions; how can one decision (by who? by justice/by court?) be rejected/dismissed?



Or is it that the decision is inacceptable to the defendant or plaintiff so they reject/dismiss it and appeal against (dismiss?) the decision?




tiles - Random map generation


I'm starting/started a 2D tilemap RPG game in Java and I want to implement random map generation. I have a list of different tiles, (dirt/sand/stone/grass/gravel etc) along with water tiles and path tiles, the problem I have is that I have no idea where to start on generating a map randomly.


It would need to have terrain sections (Like a part of it will be sand, part dirt, etc.) Similar to how Minecraft is where you have different biomes and they seamlessly transform into each other. Lastly I would also need to add random paths into this as well going in different directions all over the map.



I'm not asking anyone to write me all the code or anything, just piont me into the right direction please.


tl;dr - Generate a tile map with biomes, paths and make sure the biomes seamlessly go into each other.



Answer



Among the many other related questions on the site, there's an often linked article for map generation: Polygonal Map Generation for Games you can glean some good strategies from that article, but it can't really be used as is.


While not a tutorial, there's an article on how Dwarf fortress world maps are generated. Basically you generate multiple layers of noise, for height, moisture, temperature, salinity. Then you'd use something like this:


enter image description here


Or this


enter image description here


to generate biomes based on the layers of noise you produced before. Typically this gives a fairly smooth transition between biomes and the transitions are logical. I also modify the moisture and temperature maps based on elevation. This naturally generates a "timber line" and produces rocky mountains with snowy caps.


I'm using this strategy my game and it produces maps like this very quickly:



enter image description here


Additionally, you can see me scroll through a few more maps at the beginning of this video.


And here's some more to get you started:


How can I create a random "world" in a tile engine?


How can I identify feature regions in a procedurally generated world?


How do I create tileable solid noise for map generation?


What is the difference between future perfect and future in the past?





  1. It would be nice to buy a new car.




  2. It will have been nice to buy a new car.






Please explain the difference between these.




Thursday, October 27, 2016

how get collision callback of two specific objects using bullet physics?



I have got problem implementing collision callback into my project. I would like to have detection between two specific objects. I have got normall collision but I want one object to stop or change color or whatever when colides with another. I wrote code from bullet wiki:


int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();
for (int i=0;i {
btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);
btCollisionObject* obA = static_cast(contactManifold->getBody0());
btCollisionObject* obB = static_cast(contactManifold->getBody1());

int numContacts = contactManifold->getNumContacts();
for (int j=0;j
{
btManifoldPoint& pt = contactManifold->getContactPoint(j);
if (pt.getDistance()<0.f)
{
const btVector3& ptA = pt.getPositionWorldOnA();
const btVector3& ptB = pt.getPositionWorldOnB();
const btVector3& normalOnB = pt.m_normalWorldOnB;
bool x = (ContactProcessedCallback)(pt,fallRigidBody,earthRigidBody);
if(x)
printf("collision\n");

}
}
}

where fallRigidBody is a dynamic body - a sphere and earthRigiBody is static body - StaticPlaneShape and sphere isn't touching earthRigidBody all the time. I have got also other objects that are colliding with sphere and it works fine. But the program detects collision all the time. It doesn't matter if the objects are or aren't colliding.


I have also added after declarations of rigid body:


    earthRigidBody->setCollisionFlags(earthRigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);
fallRigidBody->setCollisionFlags(fallRigidBody->getCollisionFlags() | btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK);

So can someone tell me what I am doing wrong? Maybe it is something simple?





Past Simple or Present Perfect: Tried or Have Tried


I’ve tried to help you.
The action happened in the past but I don’t say when.


I tried to help you yesterday.

The action happened in the past but I say when.



  1. Which is correct and which is not? I’m very confused!

  2. Is there a simple rule to follow?


More Examples:


You can use the account that you’ve already created.
You can use the account that you already created.


I’ve sent you an email. Please check your Inbox.
I sent you an email. Please check your Inbox.




Answer



Which sentence is incorrect will depend upon:




  1. The country you are speaking the sentence in.

  2. Signal words you are using in the sentence &



In British English, the use of Simple Past and Present Perfect is quite strict. As soon as a time expression in the past is given, you have to use Simple Past. However in American English, you can normally use Simple Past instead of Present Perfect, so the following rules rarely apply to American English.


Signal words:



If signal words explicitly define that the event is in past, you have to use Simple Past.


eg.




  1. yesterday

  2. ... ago (an year ago)

  3. in 1990

  4. the other day

  5. last .. (last summer) etc.



Example sentence: I phoned Mary 2 minutes ago.



If signal words do not explicitly define that the event is in past, you use Present Perfect.




  1. just

  2. already

  3. up to now

  4. until now / till now

  5. ever


  6. (not) yet

  7. so far

  8. lately / recently


Example sentence: I have just called Mary.



Source (Shamelessly copied word-to-word)


word meaning - 'We are having a party this evening' - Why do we use the present continuous?


I have a sentence:



We are having a party this evening.



I don't know why we use present continuous. In grammar, we don't use having for possess.




meaning - How long is a 'block'?


I ask in an international context, and NOT only for New York. I'd cherish a picture to visualise the definitin. For example, NY Times fails to define the word, whereas the dictionaries appear conflicting and vague. Even Straightdope's apparently catholic answer hedges with the word apparently?



2.3. [North American] Any urban or suburban area bounded by four streets


4. [countable] (North American English) the length of one side of a piece of land or group of buildings, from the place where one street crosses it to the next


NY Times only worsens my confusion: 'North-south' implies 1 mile = 20 blocks, but this differs from 'The distance between avenues'? What are 'short blocks' and 'long blocks'?



Straightdope.com: Apparently the answer to the question hinges upon which city, and within that city, what is defined as a block.





graphics - Realistic metal shader


How do you create a good metal shader?


For different metals and say more or less eroded / rusty and so on.


I know that one difference from ordinary materials is that metal should 'colour' the specular light but when I do that with gold for example it just looks "yellow", not metallic at all.


Any help appreciated!



Answer



I have recently created shaders for both clean and brushed metals for my game in progress and I'm quite happy with the results.


Clean metal: The most important feature in my experiments was the environment reflections with cube maps. I implemented them with realtime render-to-texture environments, but also static images often gives good results and it's easier to blur them. The second most important feature was fresnel effect, which makes the silhuettes of the objects better. This for example gives a rounder look for balls. Specular lighting is not necessarily needed, as the cube map can provide the highlights directly. HDR rendering is also important to make the cube map reflections look good.


Brushed metal: For brushed metals you get good results quite easily by using a brush texture, something like this, together with anisotropic lighting. For anisotropic lighting you can find tutorials from the web, but I implemented my own by using blinn-phong as the base, but from the half-vector I eliminated 80% of the tangent direction. This means that you need tangents or bitangents in addition to normals in your models. The environment reflections are tricky for brushed metal. You can sample from multiple directions from the cube map based on the tangent/bitangent directions, but you might need lots of samples for good results. This however is not necessarily needed, as the texture and anisotropic lighting with multiple light sources already looks pretty nice. The end result in my case looks like this:


Brushed metal material



causatives - I will have it done by tomorrow




I will have it done by tomorrow



Would you please by some example describe what does the bold part mean?


I think the bold part is passive, isn't it?


Thanks in advance




grammar - what does mean "it there"?


In the following sentence, it seems it should end up with "like it" or "like there". Why the both of "it" and "there" have come together?




I have been to Washington several times, and I like it there.




Answer



In the sentence, it does not refer to Washington. So, you shouldn't be interpreting the sentence in this way:



✘ I've been to Washington several times, and I like (Washington) there.



Instead, it is a dummy pronoun. From Wikipedia:




A dummy pronoun, also called an expletive pronoun or pleonastic pronoun, is a pronoun used to fulfill the syntactical requirements without providing explicit meaning.



In the sentence, it does have some meaning, but it's not exactly defined. For a native speaker, the meaning of the sentence is generally the same as:



✔ I've been to Washington several times, and I like (something that exists) there.



A conversation could go something like this:



"I've been to Washington, and I like it there."
"Oh, really? What's there that you like?"




The use if it is non-specific. It refers to something, but the sentence doesn't clarify what it is. However, it does say that it exists there in Washington.


There is also a contrast between here and there (and anywhere else):



I hate (the weather) here in Antarctica, but I like (it) there in Washington.



The use of (it) has changed from a dummy pronoun to a referential pronoun because the first part of the sentence has actually made it clear what (it) is that's being referenced. But the important part is the contrast between here and there.




Compare this with the sentence in which there has been omitted:




I've been to Washington several times, and I like it.



In this sentence, no dummy pronoun is used. It is a referential pronoun that refers to Washington.


Although awkward, the sentence could be rephrased in the following way:



I've been to Washington several times, and I like Washington.



A similar conversation could be constructed around this:



"I've been to Washington, and I like it."

"Oh, really? What do you like about Washington?"



Note the specific difference between this conversation and the earlier one.


Whereas it in the first conversation refers to something completely undefined (aside from its existence in Washington), it in this conversation refers to something about Washington itself.



How to separate colliding objects without creating more collisions


Suppose I use a simple discrete collision detection system where I move all objects then check for collisions. I want any colliding objects to be separated (of course) and assigned appropriate response velocities (bounce, slide, stop, etc.).


When I have a pair of colliding objects, how do I separate them without ending up with one or both of them colliding with other objects?



Answer




This is not an easy problem to solve in general. In a physics engine it would be handled by the contraint solver. There are many different types of constraint solvers, but one of the easiest to understand is a sequential impulse solver.


Erin Catto gave a nice explanation of a sequential impulse solver at several previous GDC's, they can be downloaded from the Box2D download page, see the GDC 2009 one for example.


sound - How should a one-man team do game audio?


Most game development (game design, art, programming, etc.) can be done by one person with relatively little equipment: A game designer needs a pencil and paper, an artist Photoshop or Paint, a programmer a laptop and compiler.


Sound is different: External noises are a big problem, sound effects can't be made with instruments, and small mistakes easily produce disaster.


I can see how large companies with big studios and budgets do this.

How can I do this as a one-man indie?


Should I synthesize everything? Record sounds and buy some crazy program for editing them?



Answer



First, read these questions:



Second, there are so many musicians and sound designers of all skill levels (and expecting various degrees of compensation from free to standard rates) wanting to join on with a project. If you're having trouble finding somebody, you just need to find more internets. ModDB, GameDev.net, forums for specific engines/tools that have tried to form a general game development community. Seriously consider giving working with somebody a shot. You'll both learn a lot.


If you're wanting to be a one-man developer, then you can take a sound editor, microphone, and samples and synths, and now you're a sound guy. It's another art/craft to learn, no different in that regard to drawing/modeling/other-graphic-art, game design, and programming. Use the tools Valryon mentioned (SFXR and Audacity) to get started. Also look into:



  • Wavosaur - A freeware sound editor

  • Reaper - A very inexpensive DAW (digital audio workstation, used for producing music from audio recordings and midi) and Ardour, a FOSS alternative for Linux and OS X


  • KVRAudio.com for free basic VSTs (often playable directly in Reaper and other DAWs

  • Modplug, Renoise, SunVox, and Buzz are music trackers for old-school-style game music composition

  • Links for the lazy: Audacity and SFXR


For learning about sound, you should be aware of some of its physical properties and how we are able to digitally represent it.


To start making music, you should learn about music theory and how to produce music.


Wednesday, October 26, 2016

politeness - Is replying with just "whatever" considered rude?



Suppose that two people are talking about an event to which they participated together, and one of them says something not exact; the other person makes him notice that, but he thinks to be correct. At the end, the other person convinces him, who replies with "whatever."


Is replying with just "whatever" considered a rude way of answering to a person?



Answer



Yes, it's rude. "Whatever" expresses indifference; often, expressing indifference is dismissive, and in this case, it's dismissive of what the other person has to say. Semantically, it's equivalent to responding with "I don't care".


Being dismissive is what makes it rude. Since "whatever" can express indifference without being dismissive, it's not rude in all situations. If a friend asked me what I wanted to eat, and I replied "whatever" in a non-sarcastic tone of voice, it probably wouldn't be taken as rude. Rather, it would express that I had no particular opinion and that I'd eat whatever they wanted to eat.


xna - Isometric Collision Detection


I am having some issues with trying to detect collision of two isometric tile.


I have tried plotting the lines between each point on the tile and then checking for line intercepts however that didn't work (probably due to incorrect formula)


After looking into this for awhile today I believe I am thinking to much into it and there must be a easier way.


I am not looking for code just some advise on the best way to achieve detection of overlap



Answer



I'll come straight out and say that I don't know how to solve the problem you have described in the question (collision detection between iso-tile-shaped rectangles), but I can tell you how others have solved it in the past:


The way it's done in other games is to separate the game world from the screen world. When you're starting out, it common to imagine them being the same thing, but then it leads to problems like the one you're describing.


The general idea is that the game world is stored completely in memory, behind the scenes, it's just numbers, references, and logic. The fact that you are drawing the game world in isometric is irrelevant. Your game world shouldn't have the concept of isometric, or square, or even if the screen is being draw as 3D. All of that is taken care of when you draw the game world to the screen (aka the screen world). The game world should be stored and maintained in the simplest way that makes sense for the game, in isometric games, you typically completely ignore the fact that it's iso and instead store the positions as if you were using an axis-aligned grid. Most games will have methods for converting coordinates between the two worlds, I call mine ScreenToWorld(x, y) and WorldToScreen(x, y). The conversion is often done with Matrix math, but can be achieved other ways. You'll use ScreenToWorld when you use the mouse, and WorldToScreen when you draw.


There are several advantages to splitting the game world and the screen world. One of the advantages is that collision detection and movement all happens in the game world, and is therefore usually quite straight forward because you're not dealing with a slanted grid, or skewed coordinates, or where the screen is, etc. In your case, you'd be dealing with axis-aligned rectangles and squares. Once the game world has been updated, then you draw a representation of the game world to the screen, keyword: representation. It may seem counter-intuitive at first, but your screen is only a representation of what's going on in the game world. This makes things like dedicated servers and terminal-like clients possible.



FreeCiv is actually a great example of all these things. You can view the same exact world as any of: a square North/South Grid, Isometric, or even Hex. Every game you run has a dedicated server running in the background, even for single-player games, therefore the client is also just a display port, nothing more.


Long story short: Separating the game world and logic from the screen world simplifies the game logic, reduces the game<->display coupling, and in turn, makes collision detection between "iso" tiles easier to handle and easier to visualize.


c# - Best way to store game-wide variables


I have an options screen for things like difficulty, resolution, full-screen, etc., but I'm struggling to find the "best" way to store/obtain these variables at run-time.


Currently, I've implemented a Constants class which contains all the GameOption enums, but how do I choose a default for all of these options? Also, how do I get the currently selected enum?


Regarding the resolution, specifically, I've decided to store the values, but I'm unsure of how to get the default, or currently stored, values. Any direction would be great; thanks! :)


namespace V1.test.RPG
{

public class GameOptions
{
public enum Difficulty { EASY, MEDIUM, HARD }
public enum Sound { ON, QUIET, OFF }
public enum Music { ON, QUIET, OFF }
public enum ResolutionWidth
{
SMALL = 1280,
MEDIUM = 1366,
LARGE = 1920,

WIDESCREEN = 2560
}
public enum ResolutionHeight
{
SMALL = 800,
MEDIUM = 768,
LARGE = 1080,
WIDESCREEN = 1080
}
public Boolean fullScreen = false;

}
}

NB: I asked over at SO and they pointed me to this place. There is a comment there but I'd like to hear different ways of doing it / the most used ways.



Answer



Planning to grow:
Hard-coded constants are fine for small projects but, eventually, as your software grows in size, you will wish you could change those settings without having to recompile everything. There are many times you will want to change settings while the game is running and you can't do that with hard-coded constants.


CVars:
Once your project grows, you might want to take a look at CVARs. A CVAR is a "smart variable", so to speak, that you can modify during run-time via a console, terminal, or UI. CVARs are usually implemented in terms of an object that wraps an underlying value. The object can, then, keep track of the value as well as save/load it to/from file. You can store the CVAR objects into a map to access them with a name or other unique identifier.


To illustrate the concept a bit further, the following pseudo-code is a simple example of a CVAR type that wraps an int value:



// just some flags to exemplify:
enum CVarFlags {
CVAR_PERSISTENT, // saved to file once app exits
CVAR_VOLATILE // never saved to file
};

class CVar {
public:
// the constructor registers this variable with the global list of CVars
CVar(string name, int value, int defaultValue, int flags);


int getValue();
void setValue(int v);
void reset(); // reset to the default value

// etcetera...

private:
int flags; // flags like: save-to-file, etc.
int value; // the actual value

int defaultValue; // the default value to reset the variable to
};

// global list of all CVars:
map g_cvars;

Global access:
In the example above, I've assumed that the constructor of CVar always registers the variable with the global cvars map; this is quite useful, since it allows you to declare a variable like so:


CVar my_var = new CVar("my_var", 0, 42, CVAR_PERSISTENT);


That variable is automatically made available in the global map and you can access it from anywhere else by indexing the map with the variable's name:


CVar v = g_cvars.find("my_var");

Persistence:
When the game is shutting down, iterate the map and save all of the variables marked as CVAR_PERSISTENT, to a file. The next time the game starts, reload them.


Case law:
For a more-specific example of a robust CVAR system, check out the implementation featured in Doom 3.


Tuesday, October 25, 2016

c++ - Using HTML for interface?



The game I've been working on uses opengl/sfml for graphics. I'm currently working on the interface and I've found determining all the proper offsets/positioning etc. to be a pain. To make it configurable, I'll likely end up parsing a making a bunch of xml files to parse that tell my program what images to use/where to position them stc. for the interface.


Since I'm going to need to do that anyways, I was curious if it's possible to embed an html renderer into an app, and have it display over graphics drawn in opengl? That way i could theoretically use html pages to design the interface


If it is possible, how difficult would it be and is it a good idea? are there any projects that do this already?


Thanks



Answer



Try looking at Awesomium - it wraps the Chromium engine in a 3D renderer and HTML UIs are one of their main selling points.


unity - How can I play user-provided music stored on the phone inside my game?


I am creating a car game. Is any way to play the music stored on the phone inside the game? I'd like the player to choose files that are already on their device and hear them played in the game.


For example, in GTA Vice City game there was a folder named Music, and if we placed songs in there they would play on the car radio while we're driving around inside the game. If we want to switch the songs around, we can do so. how can I do the same in Android and iOS?


I am using unity 5.2, C#.



Answer



It is possible to do so. Given a directory, unity's WWW class will be able to obtain the file using the URL. You can then create a clip with that file and pass it to the audio source.


Do note that you will have to either hard code a directory on the phone, use a navigator to allow the user to select the folder or create a searcher to find all audio files.



Use file:// to access a local resource. Do take note that different devices have different file structure and you have to adapt for each of them.


word usage - recount to the other vs recount to each other





  1. They recounted to the other what had happened to them.




  2. They recounted to each other what had happened to them.




  3. They recounted each other what had happened to them.





Which sentence is more correct?




Monday, October 24, 2016

word order - Usage of indefinite article and too


Is there any alternative to this construction?




It was too stupid a question.



I mean, can we somehow put the 'a' in a different position and is it used in English (maybe informal) or the version I've given is the only possible? Also, I feel as if something's wrong in my previous sentence, it would be very nice if anybody corrected it.



Answer



Your sentence,



It was too stupid a question.



is good and correct. However, you can rephrase it if you'd like,




I thought (that) the question was too stupid.
Let's forget the question -- It was too stupid.
NOT It was a too stupid question.



(Please see an excerpt from a grammar book below.)




From: Practical English Usage by Michael Swan,



595 too

4 not used before adjective + noun
Too is not normally used before adjective + noun.
  I put down the bag because it was too heavy. (NOT ... the too heavy bag.)
​  She doesn't like men who are too tall. (NOT She doesn't like too tall men.)
​  Let's forget this problem – it's too difficult. (NOT ... this too difficult problem.)
In a rather formal style, too can be used before adjective + a/an + noun (see 14). Note the word order.
​  It's too cold a day for tennis.



Here is the entry 14 mentioned above:




14 adjectives (3): position after as, how, so, too
After as, how, so, too and this/that meaning so, adjectives go before a/an. This structure is common in a formal style.
​  as/how/so/too/this/that + adjective + a/an + noun
​  I have as good a voice as you.
​  She is too polite a person to refuse.
​  How good a pianist is he?
​  I couldn't afford that big a car.
​  It was so warm a day that I could hardly work.
The structure is not possible without a/an.
​  I like your country – it's so beautiful. (NOT I like your so beautiful country.)

​  Those girls are too kind to refuse. (NOT They are too kind girls to refuse.)



Preset Simple or Continuous


We can use Present Simple for things that happen time by time:



I play this game (every day)



We can use Present Continuous for things that are happening right now:



I am playing this game (now)



Also we can use Present Continuous for things that are happening in this period




I am playing this game (because for these 3 months I have someone to play with)



Then what is the difference between Simple(time to time) and Continuos for things that are happening in some period of time, if they can happen the same time to time.


In other words, what is the difference in some habit(Simple) and period of time(Continuous)?


If we have a house which we have been building for 26 years. We can say:



I build a house



because it's already become our habit(the time to time action)



And we can say:



I am building



pointing at this like at some temporal period of time, though it's for 26 years.




pronunciation - Do all native English speakers actually pronounce the "th" sound?


One of the things that were very unnatural for me while learning English was the "th" sound. Do all native English speakers actually pronounce it this way or does it vary between accents (Canadian, US, Australian, UK islands)? Does it actually stand out if I pronunce it as "f"?




Is it possible to use SFML with the Android NDK?



I've started using SFML recently and I absolutely love it. I'd like to make games that could be ported to android, linux, mac and windows, but it seems that SFML lacks portability.


I've searched for a while and I've only found unrelated or unanswered questions on forums.


Does anyone know of any way to use SFML with the android NDK or any plans to support it in the future?



Answer



I asked this few months ago, the answer is : not at the moment. It's possible but it requires some changes. Currently there is a rewriting for the 2.0 release so maybe after it's done it will be possible to add this.


As it's an open-source project I guess if there is a simple way to help the SFML author, you could propose a patch once 2.0 is done.


source : http://www.sfml-dev.org/forum/viewtopic.php?t=2503


XNA help - too much memory used?


I'm writing code in XNA 4.0, and part of my game entails drawing a textured grid of cubes. It is working, but the problem is the memory usage is growing way too rapidly. Each cube has 8 points, and each point is a VertexPositionTexture. A 16x9 grid takes 50MB memory, and that is just the grid and lines, no textures or anything else. Doubling the grid to 32x18 makes the memory jump to 150MB....I don't understand what is taking up so much room. I draw the grid using DrawUserIndexedPrimitives. The cubes can move around and be different sizes so I can't consolidate them to one set of vertices. What is the proper way to render a few thousand vertices without using so much memory?


These are all the members for my Cube class so far:



GraphicsDevice graphicsDevice; // for drawing this cube
Tileset tileset; // reference to parent object
VertexPositionTexture[] pointList; // the list of 8 vertices
BasicEffect basicEffect; // effect to draw using a shader
Vector3 localTranslation; // just 3 floats
VertexBuffer vertexBuffer; // for sending the vertices to the GPU

There are also a few functions that allocate memory for the pointList...but nothing out of the ordinary...




auxiliary verbs - When to use "am not" and "do not" in a sentence



"I don't know what I'd do without you"



"I'm not know what I'd do without you"



Are these sentences correct?


What are the rules to use "not" in a sentence?


To what is not pointing in the above sentences?



Answer



When you are negating with not, look at the finite verb in the clause, the one that carries person and tense.




  • If it is an auxiliary verb (the first verb in a verbal construction) or a form of be, you may simply add not:




    He is here. ... The verb is a form of be. >>> He is not here.
    He has arrived. ... The verb has is an auxiliary. >>> He has not arrived.
    He must have arrived. ... The verb must is an auxiliary. >>> He must not have arrived.





  • Otherwise, you require DO-support:



    He came today. ... The verb came is not an auxiliary. >>> He did not come today.

    He arrived today. ... The verb arrived is not an auxiliary. >>> He did not arrive today.
    He has a car. ... Here has is not an auxiliary but a lexical verb meaning 'possesses'. >>> He does not have a car.





Until the twentieth century it was common to negate lexical HAVE without DO-support, but this is disappearing. Even earlier any verb might be negated without DO-support, but that died out by the nineteenth century.


Sunday, October 23, 2016

phrase usage - Does "medium appearance residential buildings" express that the buildings are somewhat aged and worn out?


Is "medium appearance residential buildings" correct? Am I not sure it's correct or not?


Is it the representative of "aged and worn out residential buildings"? How else might I express this? I want a phrase that combines semi-aged and semi-worn out in one.


I am writing a scientific paper. I categorized buildings by their qualitative state in three classes. I simply want a good name for those classes. those classes were good appearance buildings, medium appearance buildings, and decayed buildings. (In the case of repair, quality of material and how rusty they are - just physical appearance.) But I think this combination is not good for repeated usage in my text.



Answer




You want qualitative terms. I'd suggest:



Well-maintained


Needing repair


Beyond repair (in a state of ruin and should be demolished)



P.S. You might consider a fourth category to be inserted above "Beyond repair", namely "Salvageable", which means "in need of a great many repairs but not in ruin yet, and worth saving". As it stands, the middle category of the three is extremely broad.


meaning in context - After how many? Usage of AFTER


For example:


If there are 5 houses in the village and I passed 4 houses and now at 5th house I finally arrived to the destination. It took me how many houses to get there or after how many houses I finally found the right place I had to get to?


After 5 or after 4 houses?


Or another example to understand me:



If I am trying to find the right video or song and I watched already watched 4 videos and now I am on 5th video and that is the video I was looking for.


And someone asks me after how many videos did you find the video you were looking for? Should I say: AFTER 5 videos or AFTER 4 videos?


Or another example:


You have had 3 girlfriends in total. 2 before and now you have 3rd and she is the one you love the most. Would you say: I finally found the right one after 2 girls or 3 girls?


The question is should I count in the one which was considered the right one?




auxiliary verbs - "did you" vs. "do you"



What is the difference between "did you" and "do you" in the following two sentences:


Did you want to schedule a meeting?
Do you want to schedule a meeting?

I can't understand this usage for "do you" and "did you" which seems to be very common. Clarification is appreciated!



Answer



"Do you want to schedule a meeting?" is very straightforward. It is inquiring if the person wants to schedule a meeting.


"Did you want to schedule a meeting?" is more complicated and the meaning can change depending on the context as well as the inflection.


It could be inquiring if what you did was actually what you intended to do.




Sir, I'm calling from the bank. We noticed you scheduled a bill payment of $100,000. Did you want to schedule it for that much?



It could be asking what you want you want. Essentially synonymous with "do you"



Sir, I'm calling from the bank. I got your message to call you about the loan we discussed. Did you want to go ahead and proceed?



It could also be discussing something you weren't able to do and inquiring if you had wanted to.



You seem upset that we went to the movie last night while you were at work. Did you want to go with us?




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