Saturday, August 31, 2019

Hardware for iPhone 2d games development


Do I need the cutting edge MacBook Pro or iMac for 2D games development?


Would a iPod touch (with Wi-Fi support) do instead of a full-fledge iPhone?



Answer



Any modern Mac that runs Snow Leopard is adequate for 2D games development.


There's nothing particularly hardware intensive about 2D game development for iOS. The most intensive things you will be doing is compiling your code and running the emulator and debugging tools - my Mac Mini did all of these tasks with ease.


The iPod touch is sufficient for testing games destined for the iPhone. The devices have the same screen resolutions, CPUs and iOS versions. The latest iPod Touch does have less memory than the latest iPhone (256MB as opposed to 512MB) so this is something you should be aware of.



sentence construction - "It’s not perfectly clear to me what it is you’re trying to say" vs. "It’s not perfectly clear to me what you’re trying to say"





  1. It’s not perfectly clear to me what it is you’re trying to say.





  2. It’s not perfectly clear to me what you’re trying to say.





Supposing (2) is grammatical, what, if any, is the difference between it and (1)?


Anyway, is (2) good English?



Answer



They both seem fine to me. I detect no difference in meaning.



I personally think the first sentence sounds better, so I think I'd be more likely to say that one. Some people prefer to say things with fewer words when possible, so I suppose they might prefer the second. But you can use either one, really.


punctuation - Is it wrong to put exclamation mark (!) after 'Thanks'?


Is the following approach wrong?



Thanks! for the LIC receipt. I am good. How are you?



Is it ok to put an exclamation mark after 'Thanks'?




Answer



A comma can take place of an interjection when expressing a weaker emotion and exclamation when expressing a stronger emotion. But, as far as I know, neither of them is correct in your case as the sentence is not independent.


Example:



Thanks! I am fine.


Thanks, but I am fine.


Thanks. I am fine.


No, it's not yours. (weaker emotion.)


No! it's not yours. (Stronger emotion.)


Thanks, John. (A comma is used here because I am addressing someone directly, but I am offsetting a name here, not the interjection.)



Well, the rain has played its part in the outcome of this match.



The following examples are wrong:



Thanks! for the offer.


Thanks, for the offer.



Why? Read the next section. :)




Now coming back to your question




Thanks! for the LIC receipt. I am good. How are you?



Here, For the LIC receipt is not a complete sentence and, hence, cannot stand on its own.


A better approach as provided by @mamtaD is:



Thanks! I got the LIC receipt. I am good. How are you?



She is right in her own sense, but this changes the meaning of the sentence. It is interesting to note that "thanks" is not used as an interjection, but as a verb(in OP's case).


A much better approach is to either put an exclamation mark at the end of the sentence or to avoid punctuating around the verb thanks.






  • Thanks for the LIC receipt! I am good. How are you?(expressing strong emotion)




  • Thanks for the LIC receipt. I am good. How are you?






Friday, August 30, 2019

meaning - What is the difference between a company, organisation, industry, firm, corporation and business?



A company is any form of business whether it is small or large.
Generally the term "company" indicates a particular kind of business dealing in a specific product.


An organisation is the larger form and generally comprises of a
number of companies. Simply, a company is an organization, but an organization is not just a company.


An industry is the combination of companies in same line of
business.


Firm, corporation and business are synonyms of "company".



An Agency is a particular kind of company, which serves as an intermediary between clients (other companies or individuals).



Is this correct?



Answer



They are all related but in different categories.


This is how they are related:



  • Industry

    • Organisation


      • Company; Profit Organisation ("Business")

        • Corporation ("Co.")


          • Public Limited ("Ltd")

          • Private Limited ("Pte Ltd")

          • Incorporated ("Inc.")

          • Trust company

          • Agency





      • Firm

        • Partnership

        • Limited Liability Company ("LLC")

        • Limited Liability Partnership ("LLP")






    • Non-profit

      • Charity

      • Foundation







Disclaimer: The chart above is incomplete as it is just to let the OP to have the image of how they are related.


Disclaimer 2: I am unsure whether Industry includes Non-profit. I don't think so, I think it includes categories of businesses like Automobile, Telephone, Internet, etc.


The most common mistake people make is the usage of Company, Corporation and Firm.


anti cheat - What are some ways to prevent or reduce cheating in online multiplayer games?



Punkbuster exists just to prevent cheating, and yet cheating is common in punkbuster enabled games. Modern Warefare 2 is seriously locked down from the end user running their own server or making any mods, and cheating happens constantly.


For a multiplayer game where each client is running on a PC, what can be done to reduce or eliminate cheating?



Answer



It depends how they're cheating, focusing on one of the primary ways of creating cheats, other processes latching into your application and modifying it - you can enumerate through all other processes, and hook their memory manipulation methods, and their keyboard/mouse emulation methods.


Wallhacks are typically written by injecting code between your process and the DirectX/GL libraries to set the transparency on materials so they can be seen through. You can add some code to your scenegraph/culling system to specifically not draw other players/useful entities if they're behind walls (to prevent cheating that way).


If you're going multiplayer and want to prevent packets being modified between client/server, then creating a checksum of the data you're sending via some algorithm of your own and checking this as it comes through on the other side can be effective. (You will probably end up doing this anyway for various QA purposes).


The same goes for most of your in-memory resources, creating a checksum at the beginning of a frame, and verifying it at various stages can yield in some pretty handy memory manipulation detection.


This is quite an involved topic, but hopefully this sets you in a vaguely acceptable direction.


c# - How can I make a gameObject "stick" to another gameObject after it has collided with it?


How can I make a gameObject "stick" to another gameObject after it has collided with it? Right now the gameObject just passes through! [C#]



Answer



In the future, you could have easily found this with a search. It has been asked many times before and is a pretty simple thing to do. You will usually not get many good answers (or any at all) if you dont search some first =-)


However, with that said:


IIRC, if both of your game objects have colliders attached to them and you catch that collision, you can use:


object1.transform.parent = object2.transform


Your collison code would look something like the following (I havent tested this and havent used unity in a while so it may be off a little)


void OnCollisionEnter(Collision collision) {
collision.gameObject.transform.parent = gameObject.transform;
}

What the above does is takes the collided object and sets its transform to your current object. That way when your current object moves, the other one should follow along. You may get unexpected results if you have a rigid body attached to these objects too, but from what it sounds like, you dont


mathematics - Changing coordinate system from Z-up to Y-up


Blender's coordinate system is different from what I'm used to, in that Z points upwards instead of Y. What would be the simplest way of converting all the world data (so that all animations, texture coordinates, etc still work) so that Y points upwards?


Clarification:


Object positions are defined as matrices, so just switching translation/rotation/scale information in matrices is not a trivial task. (at least it does not seem like a trivial task to me)



Answer




Why can't you just make the rotation matrix to orient it correctly the first part of your World matrix?


If you want to fix it when loading, create the rotation matrix to orient it correctly (i.e. 90 degrees around the X axis). Apply this to all vertices, then change all existing matrices to (rotation * existing).


word choice - Written English: not regional?


I'll be as specific as possible: Is it the case that written English tends to exclude region-specific words and expressions?


The context is the expression on the go, whose regionalism is either changing or debatable. But it can be extended to cover all region-specific words and phrases.



Also, what type of English is used in writing that excludes or tends to exclude region-specific words and phrases? Is there an internationally recognized region-free form of English?




Thursday, August 29, 2019

meaning in context - What does "feeling proud with" mean?


I've found in a Facebook post:



Feeling proud with NNN at someplace



I'm not sure about this "feeling proud with" and what it could mean?


I tried asking at English Language & Usage but it was closed as off-topic.




java - Tick() method error when I run it. HELP!


Okay so I get this error:


Exception in thread "Thread-2" java.lang.NullPointerException

at basic.game.here.Game.tick(Game.java:71)
at basic.game.here.Game.run(Game.java:54)
at java.lang.Thread.run(Unknown Source)

Here is the code it says the error relates to:


package basic.game.here;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;

import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import basic.game.here.tiles.Ground;

public class Game extends Canvas implements Runnable {

private static final long serialVersionUID = 1L;

public static final int WIDTH = 960, HEIGHT = WIDTH / 12 * 9;


private Thread thread;

private boolean running = false;

private int FPS = 0;

private World world;
private Player player;


public Game(){
new Window(WIDTH, HEIGHT, "BASIC", this);

world = new World();

player = new Player(500, 200);

}

public synchronized void start(){

thread = new Thread(this);
running = true;
thread.start();
}

public synchronized void stop(){
try{
thread.join();
running = false;
}catch(Exception e){

e.printStackTrace();
}
}

public void run() {
long lastTimeChecked = System.nanoTime();
int frames = 0;
while(running){
tick();
render();

try {
Thread.sleep(6);
} catch (InterruptedException e){
e.printStackTrace();
}
frames++;
if(System.nanoTime() - lastTimeChecked >= 1000000000){
FPS = frames;
frames = 0;
lastTimeChecked = System.nanoTime();

}
}
}

private void tick() {
player.tick();
}

private void render(){
BufferStrategy bs = this.getBufferStrategy();

if(bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLUE);
g.fillRect(0, 0, WIDTH, HEIGHT);

g.setColor(Color.YELLOW);
g.setFont(new Font("Dialog", Font.BOLD, 18));

g.drawString("" + FPS, 5, 20);

//g.drawString("(" + player.x + ", " + player.y + ")", 5, 40);

world.render(g);
player.render(g);

g.dispose();
bs.show();
}


public static void main(String[] args){
new Game();
}

}

Here is the player class because I think it is related to this:


package basic.game.here;


import java.awt.Color;
import java.awt.Graphics;

public class Player {

private int x, y;

public Player(int x, int y){
this.x = x;
this.y = y;

}

public void tick(){

}

public void render(Graphics g){
g.setColor(Color.CYAN);
g.fillRect(x, y, 16, 16);
}


}

Thanks in advance!



Answer



Your crash message indicates that Game.tick() is the source of the null reference exception:


>            Exception in thread "Thread-2" java.lang.NullPointerException at
> -- see --> basic.game.here.Game.tick(Game.java:71)

Game.tick() itself contains nothing but a call to player.tick(), so player is probably null. The player tick function is empty, so even if there were some kind of callstack trimming due to inlining, the only thing that can be null in this code is player.



Put a breakpoint on the player.tick() call in Game.tick() and verify that player is non-null; you do initialize it in the Game constructor, but after you pass the game to the window. Perhaps the window class is calling run, and thus tick() before you have executed the line of code that initializes the player.


You could also try moving the player = new Player... line up above the new Window... line.


What should a game have in order to keep humans playing it?



In many entertainment professions there suggestions, loose rules, or general frameworks one follows that appeal to humans in one way or another. For instance, many movies and books follow the monomyth.


In video games I find many types of games that attract people in different ways. Some are addicted to facebook gem matching games. Others can't get enough of FPS games.


Once in awhile, though, you find a game that seems to transcend stereotypes and appeals almost immediately to everyone that plays it. For instance, Plants Versus Zombies seems to have a very, very large demographic of players. There are other games similar in reach.


I'm curious what books, blogs, etc there are that explore these game types and styles, and tries to suss out one or more popular frameworks/styles that satisfy people, while keeping them coming back for more.



Answer



I would recommend you to read A Theory of Fun for Game Design, written by Raph Koster, an experienced game designer who started as a writer.


He basically proposes that we humans are living things that love watching and learning patterns everywhere. We basically want to get better at things, and games are a powerful learning tool. Games offer simple mechanisms that add themselves up to enable players to do really complex stuff (e.g. see how a player who loves playing fighting games learns to play those games).


What makes a player to return to a game? A fun mechanism is vital, but there is also another ingredient. Remember when you learned how to play Tic-tac-toe? it was a pretty fun game until you understood how to play it, and what strategies you used to win or tie every time. When we begin doing any activity (being playing a game, playing an instrument, painting, etc.) we start to do exactly that: learn what are the best strategies to do best what we like to do. If the activity is simple enough to know those strategies quickly, then that activity becomes boring. If the activity is too complex, we also get bored and we opt out of it.


So there are two extremes, see? assuming that we like what we are doing, if it's very simple, we will get bored quickly because our brain concludes that it took everything he needed and can predict now the next steps. If it's very complex, we will also get bored because we are unable to grasp the concepts that enables us to win the game/paint nicely/play clarinet beautifully.


So games are especialized in that: they present an activity with a carefully balanced difficulty setting, so the game is easy on us when we learn the controls, but as we gain experience playing it, the difficulty keeps rising and rising.



When we get to this fragile state of mind, we call that being "in the zone". That's an important thing to achieve when designing a game, and watch people who play if they're in the zone, whether they're playing WoW or minesweeper.


You should also read the Princess Rescuing Application slides, by Daniel Cook, which also present an insight on how games trap us.


unity - prevent animation from moving the character


As stated in the question I've this problem: I'm using Unity and when playing an animation my character moves from point A to point B without my consent. Here's the code:


public class Walk : MonoBehaviour {

private Animator humanAnimator;
private iInputProvider input;

private void Start()
{
input = new KeyBoardInput();

humanAnimator = GetComponent();
walkMe = GetComponent();
}

private void FixedUpdate()
{
walk();
}

private void walk()

{
InputWrapper inputWrp = input.GetInputValues();

animateWalk(inputWrp.verticalMove);
}

private void animateWalk(float verticalMove)
{
if (-0.1 <= verticalMove && verticalMove <= 0.1) //stand still
{

humanAnimator.SetBool("Walk", false);
Debug.Log(humanAnimator.GetBool("Walk"));
}
else if (verticalMove > 0.1) // animate walk forward if the player is walking forward
{
humanAnimator.SetBool("Walk", true);
Debug.Log(humanAnimator.GetBool("Walk"));
}
else if (verticalMove < -0.1)
{

// walk backward animation needed
}

}
}

Note that nowhere in the code I change the object position, i just start the animation. Here's the result:


https://imgur.com/OMvfmYE


note that it's not the effect of the gif, the character actually resets its position after the animation is terminated. I was expecting the character to "run on the place". Anybody has some idea how can I fix this?


EDIT: if I uncheck the "Apply root motion" check box I've this result: https://imgur.com/4FdeCKH . Maybe it could be useful to know that I can't click on "Generate root motion curve" in my animation inspector because it's all uneditable: https://imgur.com/9q3h1cd




Answer



There is an option on the Animator Component called "Apply Root Motion" this basically asks if you want the animation itself to control character motion(true, checked) or handle it yourself (false, unchecked), In your case you likely want it disabled.


for extra information on the Animator Component


If you end up on this question from google and the above doesn't help and you've also got your animations from Mixamo try re-downloading the animation with "In Place" ticked, if not ticked it applies root motion that unity cannot override.


shaders - Rotate mesh to normal


I have some instanced geometry (basic tube meshes) laid out in a grid, and I have a noise texture (normal map) that I want to use to rotate my instances with. So head pixel in my texture is a normal and I want to rotate each instance with the corresponding normal in a shader. How can I achieve that in a shader only? Unless I am mistaking, there should only be a rotation around the X and Z axes.



Answer



You can get a rotation matrix from a a direction (\$\vec d\$) and an up vector (\$\vec u\$) (direction is the normal here).


First you need to get 2 perpendicular vectors, one pointing to the right (\$\vec r\$) and one pointing up (\$\vec t\$) when looking in the direction of the normal vector.


enter image description here



You can get \$\vec r\$ by getting the cross product of \$\vec d\$ and \$\vec u\$:


$$\vec r = \vec d \times \vec u$$


Then you can get \$\vec t\$ by doing the same to \$\vec r\$ and \$\vec d\$:


$$\vec t = \vec r \times \vec d$$


The rotation matrix can be defined by these three vectors in the following way:


$$\begin{bmatrix} \vec r_x & \vec r_y & \vec r_z & 0 \\ \vec t_x & \vec t_y & \vec t_z & 0 \\ \vec d_x & \vec d_y & \vec d_z & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$$


Use it as a model matrix


Wednesday, August 28, 2019

meaning - What does *bend the rule* mean?



Malfoy certainly did talk about flying a lot. He complained loudly about first years never getting on the house Quidditch teams . . .


"He's just the build for a Seeker, too," said Wood, now walking around Harry and staring at him. "Light - speedy - we'll have to get him a decent broom, Professor - a Nimbus Two Thousand or a Cleansweep Seven, I'd say."
I shall speak to Professor Dumbledore and see if we can't bend the first-year rule. Heaven knows, we need a better team than last year. Flattened in that last match by Slytherin, I couldn't look Severus Snape in the face for weeks...."


"Seeker?" he [Ron] said. "But first years never - you must be the youngest house player in about –“
“- a century, said Harry, shoveling pie into his mouth.

(Harry Potter and the Sorcerer's Stone)



What does bend the rule mean? Does it mean change, adjust, amend?



Answer



Bend the rule means to make an exception to the rule. It means that the rule will still be the rule, but it won't apply to Harry-he can play on the Quidditch team even though he's a first year, but no other first years will be allowed (the rule will still apply to them). I think this phrase comes from the idea that the rule can be 'flexible' and change in certain situations when necessary (and if it is flexible, it can bend).


phrase usage - Can you use "Both" alone in this case?


If somebody tells me :



Do you like summer or winter ?



Is it correct if I answer :




Both.



Or am I forced to say :



Both of them.



Thank you.



Answer



As @jimsug said, they are both fine.


The word both functions as a pronoun in both of your responses: "Both." and "Both of them."



I'd like to quote this explanation along with an important usage note from Macmillan dictionary:



Both can be used in the following ways:
as a determiner (followed by a noun, but not by a pronoun): Both children are at school.
as a predeterminer (followed by a word such as "the," "this," "his," etc.): I like both these pictures. ♦ Both her children are boys.
as a pronoun: Both arrived at the same time. (followed by "of"): Both of them are learning English. (after a noun or pronoun subject): The twins both have black hair. (following a pronoun object): I like them both. (after a modal or auxiliary verb, or after the verb "to be"): We can both speak Spanish. ♦ They are both good singers.
in the expression both...and...: a method that is both simple and effective


Usage note: both
Do not use both in negative sentences. Use neither: Neither of my parents wanted me to leave school (=my mother did not and my father did not).




phrase usage - Meaning of "(assessing) points to nowhere"


A previous question post by a new user was put on hold because five people, incuding me, voted it to be "primarily opinion-based" because (or despite) it asking about one line in a song. Therefore I am restating the original post in a way that focuses on grammar.


1 In the title of this blog post, "Loyalty points to nowhere," is points a verb or a noun?


2 Also, in the phrase "assessing points to nowhere," is points a verb or a noun? The complete sentence is "And assessing points to nowhere, leading every single one."


3 Does the grammar of "assessing loyalty points to nowhere" work the same as the grammar of "assessing points to nowhere"? Edit: Please briefly explain the grammar if there is difference.


Since adding a bounty, I have added the following question:


4 Does this interpretation of the phrase act in accord with the grammar of the phrase? Why or why not?


I don't want answers that are largely opinion based, but that are grammatically, linguistically, and contextually based. Thanks.




Tuesday, August 27, 2019

physics - Math needed to create a very simple 2D side view car game


I'm trying to create a 2D side view car game (something like Hill Climb Racing, but much more simpler), but I'm confused on the math and physics.


Most of the tutorials I found were about making a top-down view game. The rest referred to the Unity3D engine, which does all the math behind the scenes and uses complex objects, whereas I'd like to achieve my goal using simple objects, such as 2D vectors and abstract them on my own (that is, without any game engine).



The project I'm working on assumes that a car is a rectangle with 2 wheels, which are ellipses. It doesn't need to brake, turn back and speed up, it should just go straight ahead (and eventually stop in case it looses all of its velocity).


An example terrain the car would be driving on:


Terrain


I can't figure out how to move the car on an irregular terrain, as well as how to rotate and move it when it falls from a hillock, etc.


Have you any idea how to move and rotate the car with respect to its current position and velocity?



Answer



I'm assuming you can understand pseudocode, and know the various terms I use. I also assume screen is defined as origin the top left and max width and max height being the right and bottom respectively where width is x and height is y. I also assume your wheels are always on the ground. I also assume your terrain is a segmented line curve.


Create your car, and assign it's center-on-screen location to a 3D vector, and do the same for your wheels if they're seperate objects. The third demension is the rotation of the object relative to the screen width, i.e. 0 rotation is completely horizontal and max is vertical. Max rotation should be ±90 degrees based on your question. Store the total height and width of the vehicle. Create your terrain, storing an array of 3D vectors, each being a location and a rotation of a line segment on screen. Also store height and width information for each of these objects. Create a gravity constant. Create a velocity variable.


Each frame: Conceptualize a line straight down from the center of the wheels by iterating and cacheing all the points where the screen point X equals the wheel center X and the screen point Y equals wheel center Y plus some small constant. Then, using those points, iterate through your terrain and find the one that intersects that line i.e. terrain.y - (terrain.width/2) < screen point y < terrain point y + (terrain width /2) and store it. This also gives you a triangle to determine the correct wheel and car angle based on the hypotenuse and the Pythagorean theorem. If the wheel intersects the terrain (same as above, just different vector now), move the wheels away from it by the difference so you stop clipping. Once you have that you can apply your gravity and velocity physics. Each frame your velocity updates to velocity - gravity if the angle of the terrain is positive or velocity + gravity if your angle is negative. Then subtract any terrain friction you might like. If your velocity is less than or equal to 0 then game over.


Not exactly the best algorithm, the iterations will impact performance at especially high object counts. The math will need tweaking if any of my assumptions are incorrect but something tells me your a smart human and will be able to adapt in that case.



Monday, August 26, 2019

Elastic Circle-Circle collision detection and response / Slime Volleyball physics


I am trying to recreate the Slime Volleyball game; however I am unsure how to go about implementing the physics of the ball movement.



The game consists of a circular ball and semi circle players that hit the ball over a net and against a wall. The ball cannot touch the floor.


I need to understand how exactly to implement the hitting of the ball against the player and what the physics entails.


I have already implemented gravity with a bouncing ball.


It is hard to find information related to implementing such physics from a game development perspective and I only have vague ideas about change in momentum from googling. If anyone could explain how to do so, I would greatly appreciate it.




physics - How to restrict jumping to a single jump?


I'm making a VolleyBall game in HTML5 with PandaJs GameEngine and plugin is used physics and Box2D.


The problem is that players can jump, but they can jump over the net with multiple jumps. I have already implemented collision detection but i don't know how the restrict move space for player. I also attaching my screen shot here so look at this : enter image description here


In the picture Player1 goes Player2 side and vise-versa.




Unity: How do I only show parts of objects that overlap [2D]


I'm working on a 2D Unity project where the player can only see objects in their field of view. I have successfully created a mesh that overlaps anything that would be in the player's field of view, but now I'm having trouble with only showing parts of objects that the mesh overlaps with.


Here is what I have so far (the gray area is the player's field of view which is a mesh:


Currently:


Here is the type of thing that I'm looking for:


Goal:


What can I do to get that desired effect? Shaders (I have no clue how to use shaders)? Colliders? Any ideas would be greatly appreciated. If there is any info you need that I didn't provide, comment and I add the necessary info. Thank you in advance!



Answer



First, create a simple mesh (such as a quad or a cube). Place it over top the actual game area, and stretch it so that it covers the entire camera view.


Next, create a new shader named "ObscurityShader", and paste in the following shader code:



Shader "Custom/ObscurityShader"
{
SubShader
{
Tags{"Queue" = "Transparent+1" "RenderType" = "Transparent"}

Pass
{
CGPROGRAM
#pragma vertex vert

#pragma fragment frag

struct appdata
{
float4 vertex : POSITION;
};

struct v2f
{
float4 pos : SV_POSITION;

};

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

half4 frag(v2f i) : SV_Target

{
return 0;
}
ENDCG
}
}
}

Everything inside "Pass" is just a bare-bones vertex/fragment shader. The most important part for us is the "Tags" at the top of the code.


Now create a new material and set it to use ObscurityShader. Select the mesh we made earlier and set it to use this material.



Next, create a second shader named "VisibilityShader", and paste in the following shader code:


Shader "Custom/VisibilityShader"
{
SubShader
{
Tags{"Queue" = "Transparent" "RenderType" = "Transparent"}
ColorMask 0

Pass
{

CGPROGRAM
#pragma vertex vert
#pragma fragment frag

struct appdata
{
float4 vertex : POSITION;
};

struct v2f

{
float4 pos : SV_POSITION;
};

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


half4 frag(v2f i) : SV_Target
{
return 0;
}
ENDCG
}
}
}


Note that this shader is near-identical to the first, with two small differences:



  1. The rendering queue is "Transparent" rather than "Transparent+1", ensuring VisibilityShader is rendered before ObscurityShader.

  2. We use ColorMask 0, which essentially sets an invisible pixel that the ObscurityShader doesn't overwrite.


Create a new material and set it to use VisibilityShader. Set your "visible area" mesh to use this material.


Finally, set your "visible area" mesh to sit above the obscuring mesh, and you should see a hole in the black void in the shape of your visibility mesh!


Final Result


c++ - How to create adjustable formula for RPG level up requirements?


I'm trying to create a formula that can be modified simply by changing two values: number_of_levels, and last_level_experience. This is to enable people modding the game to change the levelling requirements.


I've got it so that I can specify the number of XP needed for the last level up, but I want to be able to control the XP needed for the first level up, which in this case can differ wildly. For example, if I have 40 levels, and 1,000,000 XP for the last level, the first level up requirement is then 625. But if I change the levels to 80, the first level up becomes 156. In both cases, the last level needs 1,000,000.


There must be some way to get the computer to work out a suitable curve given just these two basic values.


#include 

int main()
{
int levels = 40;

if (levels < 2) levels = 2;

int experience_for_last_level = 1e6;
float fraction = 1.0 / levels;

{
int i = 0;
float fraction_counter = fraction;
int counter = levels;
int total = 0;


for (i = 1; i <= levels; ++i, fraction_counter += fraction, --counter)
{
int a = static_cast(fraction_counter * experience_for_last_level / counter);

std::cout <<"Level "<
total += a;
}


std::cout << "\nTotal Exp: " << total;
}
}

Output:


Level 1:  625   (40)      Level 15: 14423  (26)      Level 29: 60416  (12)
Level 2: 1282 (39) Level 16: 16000 (25) Level 30: 68181 (11)
Level 3: 1973 (38) Level 17: 17708 (24) Level 31: 77499 (10)
Level 4: 2702 (37) Level 18: 19565 (23) Level 32: 88888 (9)
Level 5: 3472 (36) Level 19: 21590 (22) Level 33: 103124 (8)

Level 6: 4285 (35) Level 20: 23809 (21) Level 34: 121428 (7)
Level 7: 5147 (34) Level 21: 26250 (20) Level 35: 145833 (6)
Level 8: 6060 (33) Level 22: 28947 (19) Level 36: 179999 (5)
Level 9: 7031 (32) Level 23: 31944 (18) Level 37: 231249 (4)
Level 10: 8064 (31) Level 24: 35294 (17) Level 38: 316666 (3)
Level 11: 9166 (30) Level 25: 39062 (16) Level 39: 487499 (2)
Level 12: 10344 (29) Level 26: 43333 (15) Level 40: 999999 (1)
Level 13: 11607 (28) Level 27: 48214 (14)
Level 14: 12962 (27) Level 28: 53846 (13)

Answer




Though there are infinitely many ways to choose them, it is common for leveling curves to follow a power rule such as the following one:


f(level) == A * exp(B * level)

The major advantage of this formula can be easily explained: for a given rule, there is a fixed value N such that each level costs N percent more than the previous one.


Your initial variables add the following restrictions:


f(1) - f(0) == experience_for_first_level
f(levels) - f(levels - 1) == experience_for_last_level

Two equations, two unknowns. This looks good. Simple maths give A and B:


B = log(experience_for_last_level / experience_for_first_level) / (levels - 1);

A = experience_for_first_level / (exp(B) - 1);

Resulting in the following code:


#include 
#include

int main(void)
{
int levels = 40;
int xp_for_first_level = 1000;

int xp_for_last_level = 1000000;

double B = log((double)xp_for_last_level / xp_for_first_level) / (levels - 1);
double A = (double)xp_for_first_level / (exp(B) - 1.0);

for (int i = 1; i <= levels; i++)
{
int old_xp = round(A * exp(B * (i - 1)));
int new_xp = round(A * exp(B * i));
std::cout << i << " " << (new_xp - old_xp) << std::endl;

}
}

And the following output:


1 1000          9 4125          17 17012        25 70170        33 289427
2 1193 10 4924 18 20309 26 83768 34 345511
3 1425 11 5878 19 24245 27 100000 35 412462
4 1702 12 7017 20 28943 28 119378 36 492389
5 2031 13 8377 21 34551 29 142510 37 587801
6 2424 14 10000 22 41246 30 170125 38 701704

7 2894 15 11938 23 49239 31 203092 39 837678
8 3455 16 14251 24 58780 32 242446 40 1000000

Sunday, August 25, 2019

Active voice to passive voice. Ditransitive verbs


I was asked to change voice of these sentences:





  1. He decided to sell the car.



My answer: He decided the car to be sold.


Book answer: He decided that the car should be sold.




  1. My teacher gave me a journal to read.




My answer: I was given a journal by my teacher to read.


Book answer: A journal was given to me to read by my teacher.


Why am I wrong? In same book they change She wants to insult me to She wants me to be insulted - so why am I wrong in 1st sentence?


In 2nd case there are two objects I and A journal, so I believe we can choose either as a subject, so what is wrong there?



Answer



The verb DECIDE:


In sentence (1) the lexical verb, the main verb, is : decide. The verb decide usually takes a finite clause. This means that the complement of the verb is in the form of a full sentence:



  • She decided that [ Bob should sell the car ]


  • She decided that [ Bob will sell the car ]

  • She decided that [ Bob is selling the car ]

  • She decided that [ Bob had sold the car ]


Notice that all of the complements in brackets [ ... ] look like complete sentences. This means they are FINITE clauses. They all have a modal verb or another verb with tense. In a normal sentence with decide we need a finite clause like this.


There is another type of complement that we can use with decide, a non-finite complement. We can use a complement with an infinitive. Here are some examples:



  • The doctors decided [ for him to be treated with laser surgery ]

  • Congress decided [ for him to ratify the treaty ]

  • The Court of Appeal decided [ for him to be returned to his biological family ]



Notice that this type of complement doesn't have a tensed verb. The bit in brackets cannot be a sentence on its own. It doesn't matter if we keep for or not:



  • *For him to be treated with laser surgery. (ungrammatical)

  • *Him to be treated with laser surgery. (ungrammatical)


Usually this type of sentence is very rare. We do not use this construction very much. We prefer the complement of decide to be a finite clause with a tensed verb. Sentences like the first examples are much more common.


However, there is one exception to this. If the subject of decide is the same as the subject of the complement (the bit in brackets), then we prefer to use the infinitive construction. BUT We do not usually say the sentence like this:



  • Bob decided [ for Bob to sell the car ].



With infinitive complements like this, we do not repeat the subject for the infinitive. We do not use for either. We just say:



  • Bob decided [ ______ to sell the car ].


In fact, this is the most common type of sentence that we make with the verb decide, but only if the subject of decide is being used as the subject of the infinitive. If we don't use the same subject, we prefer to use a finite clause.


If we do use the subject twice in the other type of sentence with a finite clause, that is fine as well:



  • Bob decided that [ he should sell the car ].



Notice however, that we must say what the subject of the finite clause is. If we leave it out it is ungrammatical:





    • Bob decided that [ should sell the car ]. (ungrammatical)




The Original Poster's Questions





  1. He decided to sell the car.



Here the sentence uses an infinitive complement. This is because it means:



  • He decided [ for himself to sell the car].


Because we understand that the subject of decide is the subject of to sell we can use the infinitive construction. But if we make the complement passive we get this:




  • He decided [ for the car to be sold by himself ].


Now the subject of decide is 'he' but the subject of to sell is 'the car'. Because the subjects are different we must say who the subject is. But we don't like the very unusual infinitive complement, unless we can leave the subject out. It is much more normal to use a finite complement:



  • He decided that [the car should be sold].




  1. My teacher gave me a journal to read.




The Original Poster is correct here. They can use either the direct object a journal or the indirect object me as the subject of a passivised sentence:



  • I was given a journal to read.

  • A journal was given (to) me to read.


Hope this is helpful!


Saturday, August 24, 2019

xna - Farseer: How can I calculate the needed velocity in this case?


I have two platforms and one ball. The ball should fly from the red platform to the blue platform. The ball should land somewhere in the purple rectangle of the blue platform.



How can I know how fast the linear velocity of the ball should be to accomplish the jump of the ball? Is there a mathematical formula to calculate the linear velocity(x,y) which should be added to the ball so that the ball can jump to the blue platform?


The ball should always land in the purple area.


Distance(width) from the ball to the target: 212 pixel


Distance(height) from the ball to the target: 52 pixel


The distances were measured from the center of the ball to the center of the purple rectangle.


The gravitation of my world is world(0,3).



Upadte I use the following formula for the impulse:



impulse = Vector2(distance.x / time * mass + gravity.x / 2 * time * mass, distance.y / time * mass + gravity.y / 2 * time * mass);



mass: mass of the ball


It's working with this formula, but only if the value of the time is not too low. time = 2.0f(or higher) is working but if I use time = 1.0f, then the ball is touching the left side of the blue platform.


Why is the formula not working with low time values? I don't understand that.



Answer



Short answer:


impulse = (gravity * time*time + distance * 2.0) / (time * 2.0);


(or optimized for the specific numbers you asked for)


impulse = Vector2(212.0/time, 52.0/time + 1.5*time);

(although, I think maybe you wanted this one that accounts for gravity but can be used to calculate any possible jump)


impulse = Vector2(distance.x/time, distance.y/time + 1.5*time);



Long answer: (pre-calculus required)


First express your problem mathematically:




Integrate to find that:



Solving this for impulse yields:



Which is our answer, notice that time is still unknown in this system. This means there are infinite trajectories that will land on the purple rectangle. You have to decide how long it should take.


selection - How to handle focus on a custom actor in Unreal Engine?


I created a custom actor, placed it on my scene and selected it.


When I press "F" to focus on it, the camera zoom back very far from the scene, probably because I didn't implement the method supposed to return the bounding box of my actor.


How can I do that?


Update



I implemented a custom component which delegates all drawing functions to an internal ULineBatchComponent member. I unregistered this ULineBatchComponent member. The custom component is not even attached to the actor root component.


But its bounding box is still taken into account when focusing on the actor.


UPBLineBatchComponent.h


UCLASS()
class UPBLineBatchComponent : public UObject
{
GENERATED_UCLASS_BODY()
public:
virtual FBoxSphereBounds CalcBounds(const FTransform& LocalToWorld) const;
void SetTransform(const FTransform &Transform);

virtual void DrawLine(...);
virtual void DrawPoint(...);
void Flush();
ULineBatchComponent* LineBatchComponent;
FBox LocalBounds;
};

UPBLineBatchComponent.cpp


UPBLineBatchComponent::UPBLineBatchComponent( const FObjectInitializer& ObjectInitializer )
: Super( ObjectInitializer )

{
LineBatchComponent = CreateDefaultSubobject(TEXT("LineBatcher"));
LineBatchComponent->UnregisterComponent();
LocalBounds = FBox(0);
LineBatchComponent->Bounds = FBoxSphereBounds(EForceInit::ForceInitToZero);
}

FBoxSphereBounds UPBLineBatchComponent::CalcBounds(const FTransform& LocalToWorld) const
{
LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));

return FBoxSphereBounds(LocalBounds.TransformBy(LocalToWorld));
}

void UPBLineBatchComponent::SetTransform(const FTransform& Transform)
{
LocalBounds = LocalBounds.TransformBy(Transform);
LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);

bool bDirty = false;
for (FBatchedLine& Line : LineBatchComponent->BatchedLines)

{
Line.Start = Transform.TransformPosition(Line.Start);
Line.End = Transform.TransformPosition(Line.End);
bDirty = true;
}

for (FBatchedPoint& Point : LineBatchComponent->BatchedPoints)
{
Point.Position = Transform.TransformPosition(Point.Position);
bDirty = true;

}

for (FBatchedMesh& Mesh : LineBatchComponent->BatchedMeshes)
{
for (FVector& Vert : Mesh.MeshVerts)
{
Vert = Transform.TransformPosition(Vert);
bDirty = true;
}
}


if (bDirty)
{
LineBatchComponent->MarkRenderStateDirty();
}
}

void UPBLineBatchComponent::DrawLine(const FVector &Start, const FVector &End, const FLinearColor &Color, uint8 DepthPriority, float Thickness, float LifeTime)
{
LineBatchComponent->DrawLine(Start, End, Color, DepthPriority, Thickness, LifeTime);

LocalBounds += Start;
LocalBounds += End;
LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);
}

void UPBLineBatchComponent::DrawPoint(const FVector &Position, const FLinearColor &Color, float PointSize, uint8 DepthPriority, float LifeTime)
{
LineBatchComponent->DrawPoint(Position, Color, PointSize, DepthPriority, LifeTime);
LocalBounds += Position;
LineBatchComponent->Bounds = FBoxSphereBounds(LocalBounds);

}

void UPBLineBatchComponent::Flush()
{
LineBatchComponent->Flush();
LocalBounds = FBox(0);
LineBatchComponent->Bounds = FBoxSphereBounds(EForceInit::ForceInitToZero);
}

Update 2



If I use


LineBatchComponent = NewObject();

instead of


LineBatchComponent = CreateDefaultSubobject(TEXT("LineBatcher"));

I can focus properly on the actor, but I can't see the lines anymore.



Answer



I've never experienced the problem you're describing with any custom actor types. You shouldn't need to do anything explicitly, or implement any methods, yourself.


The "focus" command is handled in EditorServer.cpp (the link requires access to Epic's private Unreal Engine GitHub, which can be obtained by registering an account with Epic); specifically UEditorEngine::MoveViewportCamerasToActor.



This method computes a bounding box for the viewable region based on the bounding boxes of the individual selected actors and their components.


Based on your problem description, it is likely that your actor, or one of its components, has an improperly initialized or overly-large bounding box assigned. The other possibility would be that your actor has no components, and is configured such that all other code paths computing the bounding box are skipped (certain types of actors, et cetera), resulting in a zero box.


However the subsequent call that actually focuses the viewport on a box will early-out if given a zero box, so it's quite likely the case is the first one: one of your actor's components has an overly-large or malformed non-zero bounding box.


conditional constructions - "had I stayed" or "if I had stayed"?


Could you explain to me which structure was used in this sentence in the following passage.



I developed into a very different person than I would have done had I stayed in Australia...



Should it be written also like :




I developed into a very different person than I would have done if I had stayed in Australia...



enter image description here




Friday, August 23, 2019

shaders - Math behind XNA's spriteBatch.draw() color parameter?


I'm trying to make a shader that changes the color of a sprite the way the XNA spriteBatch.draw() color parameter changes color. I don't know exactly what it is called (the closest word I can think of is 'tinting' but that's not right I don't think) and it's kind of hard to explain the way it looks.


Say you set the parameter to 'Red' -- white pixels in the original texture would become completely red, while black pixels would remain black. Grey pixels would look dark red, blue pixels might look purple, green pixels might look brownish.


If you set the parameter to 'Black' the texture would become completely black.


Does anyone know the math behind this, or what this technique is called? It's probably very simple and I'm just not seeing it.


Thanks!



Answer




It's probably multiplying the colours. That's pretty typical for a parameter like this.


Each colour channel is interpreted as a value from 0 to 1, then multiplied with the corresponding colour channel of the tint colour. So:


_______________ times red (1, 0, 0)  =
white (1, 1, 1) = red (1, 0, 0)
grey (0.5, 0.5, 0.5) = dark red (0.5, 0, 0)
black (0, 0, 0) = black (0, 0, 0)

Under this scheme, pure blue (0, 0, 1) tinted with pure red (1, 0, 0) will turn black. But if you use intermediate blue & red colours (ones with some non-zero values in the other two channels) you may get a dark purple.


Here's an example of using "multiply" blending to tint colours, via this tutorial Multiplication tinting example


phrase request - What do you say when time-out is over


You put your naughty child on time out at (in?) the end of the room for example, and then when the time of punishment is up you want them back with you. How do you address them and tell them to come and join you?


Are these two sentences: "come out of there", or simply "come out there"




  1. correct or incorrect

  2. natural or awkward


What do you personally say at home (of course if you use this kind of parental discipline)?


PS: By the way, is it at the end of the room, or in the end of the room?



Answer



I would probably say:



"Okay, it's time to come out."




or:



"Your timeout is over now; come on out."



I think "come out there" sounds very awkward. "Come out of there" is passable, but I see that being used when you're sharply telling someone to come out of some enclosed area, like a large box, a swimming pool, or a doghouse:



"Joey! Come out of there! Right now!"



As for at vs in (the end of the room), most timeouts are given in the corner of a room. In fact, if you look up "in the corner" on Google images, you'll see several pictures like this one:



timeout


If the child is to stand in the corner, then the preposition is indeed in:



"Go stand in the corner."



However, if the child is supposed to stand somewhere along the middle of a wall in the room, and you wanted to call that location the "end of the room," I would probably use at:



"Go stand at the end of the room."



(For some reason, that makes me imagine a room that is more rectangular than square, where the punished child is to stand at the wall with the shorter end that is furthest away from the door – like where I've put the red ‘X’ is this blueprint:



at the end of the room


That's where I'd go stand, if you told me to stand "at the end of the room."


grammaticality - Two consecutive gerunds? -ing -ing?




  1. I am considering to set up a cyber cafe.

  2. I am considering setting up a cyber cafe.



I think it should be version #2 where the verb considering is followed by the gerund setting. But it sounds unnatural to me.



Can we use a gerund after "Verb+ing"?



Answer



Yes.


To native ears, the two consecutive gerunds don’t sound especially remarkable even though they both end with -ing. The construction is fairly common:



The contractor is delaying building the front porch.


We’re risking missing our plane.


I'm imagining writing a silly ending to this answer.



Three gerunds in a row is unusual but tolerable:




Some doctors are considering stopping recommending high-carbohydrate diets.



Four gerunds in a row sounds silly, though it’s still grammatically correct:



I’m enjoying imagining finishing writing this answer.





A Google search turns up 55,000 books that contain considering setting up.


word usage - Is it good to call someone "Nerd"?


My friends always use "nerd" to describe an intelligent person, but when I searched its meaning online, I found that it's not really a good word.



"A foolish or contemptible person who lacks social skills or is boringly studious."
Oxford Dictionaries


I've become so confused with this word.
Is it an insult or a compliment?



Answer



If they are referring to an "intelligent" person like you say then they most probably mean:



a person who is extremely interested in one subject, especially computers, and knows a lot of facts about it — Cambridge Dictionary



Example,




I'm a real grammar nerd.



So, no it is not in the bad or negative sense but you still have to be careful with this word some people might find a bit offensive to be called a "nerd" especially when this word has a first definition that is kind of negative.


Thursday, August 22, 2019

grammar - 'all of which' vs. 'any one of which' vs. 'each of which'



1) ... if you tried to compare can't with cannot and can not, all of which are distinct in English, you'd end up ...


2) ... if you tried to compare can't with cannot and can not, any one of which is distinct in English, you'd end up ...


3) ... if you tried to compare can't with cannot and can not, each of which is distinct in English, you'd end up ...



Which one is good English, and why?




Answer



All OP's examples are perfectly good English, though (2) is perhaps a little odd in this exact context. And obviously, in this context, they all mean exactly the same thing.


But there are contexts where they're not so interchangeable (to a considerable extent, deriving trivially from the semantics of the specific words in the various idiomatic forms).





1: More than 10 additional Eocene species are known, all of which are American.



...where both any one of which and each of which would be completely unacceptable to me. Why suggest isolating one out of 10 species when the whole point is that they're all the same ("nationality", at least)?






2: Millions of these brakes have been discarded in unknown states of repair, any one of which could explode in the hands of a curious child.



...where any one of which is by far the best choice, since it accentuates the fact that if even one goes off, that would be pretty bad.





3: The team is then asked three questions, each of which is worth five points.



...where any one of which is a bad choice because it misleadingly isolates a single question (implying the team might only answer one). And all of which are is bad because it could easily be misinterpreted as meaning all three questions are worth five points collectively, in total (if they're all answered correctly).




One similar permutation that OP missed out (and which I personally prefer in this exact context) is...




4: Sometimes it is possible to break down long compounds into single elements of one syllable each, every one of which is distinct in meaning.



...where I honestly can't explain why I prefer every. There's nothing wrong with OP's every or all versions there (though again, any one of which doesn't work because of the unwanted "particularisation").


unity - Does `yield return false;` have special meaning in Unity3d C# scripts?



In Unity, we have some special things for coroutines that are additional to normal C#.


for example, we can use


yield return WaitForSeconds(5.f);


to have a coroutine wait 5 seconds before continuing.


What do yield return false; and yield return true; do?



Answer




The only possible yield values the scheduler understands are:



  • Classes derived from YieldInstruction (WaitForSeconds, WaitForEndOfFrame, WaitForFixedUpdate, AssetBundleCreateRequest, AssetBundleRequest and Coroutine


  • a WWW object

  • "any other value" which isn't one of the above.


If "any other value" is yielded (which includes "null" a string value any other basic type such as int, bool, ... or a reference to an arbitrary object which isn't one of the above mentioned) the scheduler will "schedule" the coroutine for the next frame.


- Bunny83 answer: Prominent member on Unity Answers



The WaitForEndOfFrame and others of the like, are just blank functions that tag the YieldInstruction in order to decide what to do in the engine.


The default case seems to be WaitForEndOfFrame. So if you yield return something that doesn't have a special meaning, such as a bool, it is the same as WaitForEndOfFrame.


There doesn't seem to be any official documentation on this behavior.





Update


rutter commented about another special case: yield return null


All of the Unity Coroutines including yield return null, run before the frame renders except for WaitForEndOfFrame. You can find rutter's awesome answer over at Unity Answers explaining this further (nice diagrams included).


unity - How do I reference one game object in a script attached to another?


This is all in Unity, with C#.


I have attached a script to my player that should destroy a TreeGroup (as in a forest) whenever I press 'Q' and instantiate one when I press 'E'.


Here is the code:



using UnityEngine;
using System.Collections;

public class DisableTrees : MonoBehaviour {

// Use this for initialization
void Start () {

}


// Update is called once per frame
void Update () {

if (Input.GetKeyDown (KeyCode.A)) {
//Disable Trees on A Keypress

Debug.Log("Trees Disabled!");
}

if (Input.GetKeyDown (KeyCode.E)) {

//Enable Trees on E Keypress

Debug.Log("Trees Enabled!");
}

}
}

How do I access and find my 'TreeGroup' object group while script not being attached to 'TreeGroup' but my character instead and then Destroy on Q Keypress? And how do I Instantiate it?




Wednesday, August 21, 2019

assets - Where can I find fonts for my game?




Where can I find fonts (preferably free, but a reasonable fee is acceptable) that I can use in my for-pay/commericial game?



Answer



You can find many free and cheap fonts on MyFonts.com, including the Larabie Font Collection (many of which are free for commercial use)



unity - Season Change Reveal Effect


I was watching the teaser trailer for Seasons After Fall, and I was struck by the effect they use to transition between seasons (around 21-24 seconds):


Animation showing the reveal effect


The level art, including the background and the foreground platforms, change from a sepia-coloured autumn to a lavender winter, with the effect spreading outward from the player character a bit like water soaking through paper.



It looks like more than just a palette change, as details in the leaf and bark patterns change in the transition.


How could I achieve an effect similar to this in a 2D Unity game?



Answer



One way to accomplish this would be to blend between the two backgrounds using an alpha map. A simple approach would be to render the "back" (hidden) background, and then the "front" (initially-visible) background. Use the alpha channel of the front background, or a separate alpha texture, to control the transparency of the front background as you would any transparent or translucent sprite. Where this alpha map is less than one, parts of the back background will show through.


Then it's just a matter of building that alpha map according to the effect you'd like. In the video you show off, it looks like such a map was built with a "painterly" kind of approach. This might involve randomly placing circles of zero alpha (that feather off to 1.0 alpha around their edges). Start placing these circles tightly biased around the origin of the reveal, and over time relax the bias so they spread outward. As you do this you'll probably want to expand the radius of the circles as well.


You can tweak this approach as you need it to tailor the effect to your desires; plain circles might end up looking a little too "blotchy" for example, and you might instead want to randomly stamp a randomly-selected pre-authored "brush stroke" into the mask instead. Even random placement itself might look a little too disorderly, and you might instead opt for stamping the alpha mask along some pre-authored curve or spline to highlight a particular style.


word order - How to properly position adjectives



Sometimes I find myself in the position to describe something and of course making massive use of adjectives. Check out the following sentences, I would say, for example:



  • three large red apples;

  • three red large apples;


are equally correct, I think but I've never heard anyone say:



  • large three red apples;

  • large red three apples...



and so on. I don't know if there actually exists any specific rule, but in which order should adjectives be put? Is there a right way to list them?



Answer



The order used to write adjectives should be the following one, basing on the category of the adjectives:



  • Opinion

  • Size

  • Age

  • Shape

  • Color

  • Material


  • Origin

  • Purpose


In your case, the order should be: three, large, red.


The linked paged doesn't say where to put numerals, but I would put them before every adjective.


algorithm - C# Minesweeper - When cells with no mines nearby gets clicked


I'm currently making a Minesweeper in C#. I've already done the basics (generating minefield, rules and ui) but I don't know how I should implement when the user clicks a cell and the cell has no mines nearby and clicks nearby cells with also no mines nearby, like this:


Minefield before click


And after click


Minefield after click


This is my current code on this:


if (MineField(x,y) == false) // If the clicked cell isn't a mine

{
if (GetNeighbours(x,y) == 0) // GetNeighbours returns the amount of mines in the closest 8 cells
{
// To be honest, no idea...
}
}

Answer



One way to do this, is to use recursive Flood Fill algorithm. Something like:


If cell(x,y) has no bomb: 1. If coordinates (x,y) didn't went beyond game board, and cell (x,y) wasn't marked as visited:


a) give cell (x,y) property visited to true (or mark it in any other way) b) if getNeighbours(x,y) > 0: print number of cell (x,y) c) if getNeighbours(x,y) == 0: reveal cell (x,y) and call whole function responsible for revealing field for coordinates (x-1,y-1),(x-1, y), (x-1, y+1), (x, y+1), (x+1, y+1), (x+1, y), (x+1, y-1), (x, y-1).



meaning in context - Free as in "free speech", not as in "free beer"



Free software is a matter of liberty, not price. To understand the concept, you should think of free as in free speech, not as in free beer. — Richard Stallman



Translating free to my language (Ukrainian), generates a huge variety of different terms, including (I apologize for my lame translation back to English) independent, unleashed, loose, at no cost (of manufacture), at no price (for a buyer), at no extra fees/taxes, useless, fired (from a job), or done (completed a work).


What is actually the difference between the two meanings in the phrase above, and how should I understand the term of "free software"?


I'm aware you can't fire a beer from a job, :) but there are still too many overlapping meanings.



Answer



"Free software" as used by the Free Software Foundation is a difficult term to translate into many languages, and they even admit as much. I couldn't find the exact page where they do with a quick look around their web site, but I know I've seen it there.


It can mean either software that is offered free of charge, or software which comes with certain freedoms (for the user). The difference is between free of charge and freedom.



Like the author says, think of "free beer" versus "free speech". "Free speech" is not generally taken to mean speech that is made available at no cost, and "free beer" is not generally taken to mean beer for which you receive the exact recipe, the right to change it (or not) and hand out or sell your own.


Note that different organizations have slightly different meanings for "free software" even when referring to freedom. The general gist, however, largely remains the same.


You sometimes see "free software" when used this way written with a capitalized Free (Free software) to emphasize the difference from free-as-in-at-no-monetary-cost.


To quote the FSF (my emphasis):



When we call software “free,” we mean that it respects the users' essential freedoms: the freedom to run it, to study and change it, and to redistribute copies with or without changes. This is a matter of freedom, not price, so think of “free speech,” not “free beer.”



It's also worth noting that in this specific context, even the FSF does go as far as to actually say that selling free software is OK.


opengl - How to get PS3/Xbox 360 experience without having access to Dev kits?


I am a budding game programmer trying to get into the industry programming for PS3, Xbox 360. The main problem I see is the need to demonstrate my skills to a potential employer, but without access to Dev kits for the PS3 or Xbox 360, doing this directly is impossible.



My question is, what is the best alternative way to show console developers my skills?


C++ programming in DirectX for Windows seems close to showing Xbox 360 programming skills, and C++ programming in OpenGL seems relatively close to showing PS3 programming skills. Unfortunately, it seems from web research as if both Xbox 360 and PS3 actually have their own propietary libraries, therefore seeming to make this not a 100% fruitful endeavor. This approach seems closest, but also most time consuming. Plus you're not actually making anything run on the console.


On the other hand, programming in XNA has the benefit that your games are actually on the console, though I get the impression that this is looked upon as not "the real deal" since it is just a wrapper around DirectX and uses C# instead of C++.


Does anyone have knowledge or experience from inside the industry so as to know what kind of game demos would be most useful to show to a potential employer? C++ in DirectX, OpenGL, XNA, Unreal Engine, Unity3d, Flash, etc etc etc? There are only so many hours in the day, and I'd love to know how to direct my efforts.


My gut feeling is that DirectX would be the best choice, as it seems closer to what is used on the Xbox 360, but if having a good demo in another language/engine is just as good, it would obviously be less time consuming to go another route.


Thanks in advance for your help and advice!



Answer



Depends what path you are going down, frankly most people don't expect specific platform skills in a junior.


If your a games programmer, make a lot of games.


If your a technical programmer make a load of tech demos. Read interesting white papers and try new stuff out. If you do something interesting that makes the programmers go OOOoo we will WANT to talk to you. We want to chat about this little interesting thing you have done. It doesn't need to be a game.



KEY FACT: Your demo's should run on a wide range of machines, include a video recording as a back-up. Edited not raw.


grammar - We each has/have?



I'm confused by the following sentences:




  1. Each of us has a laptop.

  2. We each have a laptop.



How can I intuit the differences between the two sayings? Why is it "we each have" rather than "we each has"?



Answer



One of the key rules for understanding subjects is that a subject will come before a phrase beginning with of. The word of is the culprit in many, perhaps most, subject-verb mistakes.




Incorrect: A crate of sardines are* more expensive than I thought.
Correct: A crate of sardines is more expensive than I thought.



In addition, the words each, each one, either, neither, everyone, everybody, anybody, anyone, nobody, somebody, someone, and no one are singular and require a singular verb.



Each of these hot dogs is juicy.


Everybody knows Mr. Jones.



As for "We each have a laptop", in my opinion, it is a sloppy sentence compared with "Each of us has a laptop" or "We all have laptops".



If the intention were to use "each" as an adverb, it would and should be placed at the end of the sentence: We have laptops (,) each (of us).


And here's the final point:


With words that indicate portions—e.g., a lot, a number, a majority, some, all. etc.— the previous rule is reversed—and we are guided by the noun after of:


If the noun after of is singular, a singular verb is used. If it is plural—a plural verb.



A lot of the pie has disappeared.


A lot of the pies have disappeared.


A third of the city is unemployed.


A third of the people are unemployed.


All of the pie is gone.



All of the pies are gone.


Some of the pie is missing.


Some of the pies are missing.



Here's one of the numerous sources.


Tuesday, August 20, 2019

"turn down the volume" or "turn the volume down" - phrasal verb structure



I'm learning about phrasal verbs, but I'm not sure if I'll use them correctly. Which one of the following phrasal verb uses correct:




-I don't know how to turn down the volume?


-I don't know how to turn the volume down?



I always think that they're same, but lately I feel like there must be a rule how to use them correctly, or perhaps they get different meanings?



Answer



They're both fine, and they mean the same thing. The particle down can appear before or after the object the volume:



1a. I don't know how to turn the volume down.
​1b. I don't know how to turn down the volume.




However, if the object is an unstressed personal pronoun, down has to come at the end:



2a. I don't know how to turn it down.
2b. *I don't know how to turn down it.



I marked example 2b with an asterisk * to indicate that it's ungrammatical.


By the way, if the object is very long or complicated, down usually appears beforehand, because it would be confusing to keep the listener waiting to hear the rest of turn down:



3a. ?I don't know how to turn the volume on the stereo receiver attached to the TV over there down.

3b. I don't know how to turn down the volume on the stereo receiver attached to the TV over there.



I marked 3a with a question mark ? to show that, although it's grammatical, it's not a very good sentence. With such a long object, it's better to put down beforehand.


c# - Decoupling input from game states / entity behavior


I'm looking for a way or general best practice advices for decoupling the architecture of my game, in the example below the input from the current game state workflow / entity behavior. While I'm all in for certain game development (or general) patterns such as an event- or component-driven design, I'm failing to understand how a decoupled architecture can work in a case where e.g. an entity actually needs to know a little bit more.


Take for example this little (bad) example:


// some component attached to an entity
void Update(long elapsedTime) {
var keyboardState = _keyboardDevice.State;
var gameState = _gameStateStack.CurrentState;

if(keyboardState.IsPressed(Keys.Enter) {
if(gameState.GetType == typeof(MenuState))

((MenuState)gameState).ExitMenu();
} else {
parent.Jump();
}
}
}

The requirements are pretty simple: If we're in the game menu, pressing enter closes the menu. However if the menu is not active, pressing enter causes the entity to jump. If I'm going to decouple the menu and the entity component using an event-driven approach...


// menu state
class MenuState : IHandle() {

void Handle(KeyCommand keyCommand) {
if(keyCommand.Key == Keys.Enter && keyCommand.IsPressed)
...
}
}

// entity component
class EntityControllerComponent : IHandle() {
...
}


... the concerns are clearly separated. But what happens now if I press the ENTER key? Who decides which part of the game is allowed to actually receive and handle the event?



Answer



Input is hard. Most of the simple patterns you see frequently in game dev just don't work well for input, at least at the low level.


Typically, for any kind of GUI, you need to have some concepts of focus and possibly also bubbling. The HTML/DOM model here is a good resource.


In such a setup, there is a sorted queue of event listeners. For a GUI, this would be a stack of widgets starting from where focus lies. For games, this might be the stack of game states or overlay panels. The input event is either only delivered to the top-most listener (so any overlay implicitly "blocks" all others from receiving input) or is handed to each in turn (giving each a chance to optionally block the remaining listeners from receiving the event).


There are weird complexities with input handling, too. For instance, in many input designs, you differentiate between KeyPressed and KeyReleased events. However, if you just deal with those naively, it becomes possible for one listener to receive the KeyPressed for a particular key and a completely different one to receive the KeyReleased. The first system might have some important logic that must be run after the release but it never finds out about it. You can see this in some games where you start moving, a dialog pops up, and the character continues moving even though you've let go of the movement key.


A solution for the above then is to remember which listener received any particular KeyPressed or ButtonPressed event and ensure that it receives the corresponding release events independent of which listener has priority. Likewise, if the whole app is unfocused (say via alt-tabbing away) then the input module can be sure to send simulated release events to any listeners that had received press events.


I can't stress enough: you basically have to use a pattern like that for handling the input at an application level.


Now, within the game itself, that is all inconvenient and wrong. You don't want your character controller to be dealing with input priorities and event canceling. In fact, you almost certainly don't want your character controller even handling low-level input events: the controller shouldn't have to figure out whether a key was Space or RightArrow. It just wants to know that the user pressed the JUMP key or that the right wants to move right.



This generally means you have an intermediate high-level gameplay input module. It registers into the input event priority list and then translates the low-level input events that it actually receives (individual key presses and the like) into generic gameplay-relevant events. It handles key mapping and rebinding, it handles abstraction gamepad input from keyboard input, and so on. The entire rest of the gameplay systems can then just deal with simple events while all the complexity of input focus is localized to that one gameplay input module.


TL;DR: use a priority list of input event listeners for low-level input and simple game events for high-level abstract gameplay controls.


Monday, August 19, 2019

java - LibGDX: Issue with unitScale for Tiled and Box2D


I've got the following: I use a TiledMap (loaded from a .tmx), each tile 32x32 pixels in size and generate the Box2D bodies for collision from the TiledMap's ObjectLayer. That all works fine, no errors or issues. The only thing is a very strange behavior of the OrthogonalTiledMapRenderer: It gets a unitScale with the value 1 / 32 (because one unit is 32 pixels) as advised on the LibGDX GitHub wiki page. The same unit scale is used for Box2D. Thought in theory this should work just fine it renders the map very small (same is the case for the Box2D bodies, they're shown very small by the Box2DDebugRenderer):



enter image description here


Here is my code (more or less simplified):


public class MainScreen {
private OrthographicCamera camera;
private ScreenViewport viewport;
private SpriteBatch batch;
private World world;
private TiledMap tiledMap;
private OrthogonalTiledMapRenderer tiledMapRenderer;


public MainScreen() {
this.batch = new SpriteBatch();
this.world = new World(new Vector2(), true);
float unitScale = 1.0f / Constants.TILE_SIZE;

this.camera = new OrthographicCamera();
this.camera.setToOrtho(false, Gdx.graphics.getWidth() * unitScale,
Gdx.graphics.getHeight() * unitScale);
this.viewport = new ScreenViewport(this.camera);
this.tiledMap = (new TiledMapLoader()).load("level/test-level.tmx");

this.tiledMapRenderer = new OrthogonalTiledMapRenderer(this.tiledMap,
unitScale, this.batch);

// Create bodies in world based on map
Collisions.create(this.world, this.map, unitScale);
}

public void render(float delta) {
// Clear the screen
Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

this.world.step(delta, 6, 2);
this.camera.update();
this.tiledMapRenderer.setView(this.camera);
this.tiledMapRenderer.render();
}

public void resize(int w, int h) {
this.viewport.update(w, h);

}
}

I've got no idea why this is happening... Thanks in advance :)



Answer



I just stumbled upon the answer:


I checked my ScreenViewport and seemingly the viewport somehow ignores the setToOrtho(false, width, height) and the method setUnitsPerPixel(unitScale) has to becalled first...


I never saw an example in which a viewport was used together with box2d, tilemap and unitScale, so I didn't even know about that method.


The greatest thanks to @Shiro for his help! :)


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