Sunday, March 31, 2019

phrase request - What tense should I use?


I am trying to translate a sentence about having breakfast from Italian, but I don't know which tense I should use.



Facevo colazione alle 9:00.



The sentence is about something done in the past; it's not something done in the present days or in the foreseeable future. It is about something done more than once, but nothing is said about the periodicity (it could be every day, once per week, or when there was the occasion). Nothing is said about when the action was not anymore done; I could have stopped one year ago, or a week ago. Every time I had breakfast, it was 9:00 AM.



I thought to use the following sentences, but each of them sounds not correct, for a reason or another.



I had breakfast at 9:00 AM.



It seems talking of a single event; without nothing else being said, I would take the sentence as referring to the past 24 hours.



I have had breakfast at 9:00 AM.



I would understand it as talking about something habitual, but that still happens.




I had had breakfast at 9:00 AM.



The Present Past alone, as far as I recall, it is not used in a simple sentence.



I was having breakfast at 9:00 AM.



It seems talking of a single event. Different from the first one, this sentence seems saying that at 9:00 AM I was not done with having breakfast.


To give more context, imagine that I move to New York, somebody asks me "How was your live before moving to New York?" and I answer with "It was wonderful." I then list what I liked to do and I am not anymore able to do. What tense should I use in that list?



Answer



I think StoneyB is right that, in English, we generally require more context to be sure your meaning gets across. That being said, what you're asking for is kind of vague; it seems likely that there would be questions asked in response to get further information. So I think your best bet is this:




I have had breakfast at 9:00 AM.



This is indeed quite vague; sometime in the past, at least once but possibly more than once or even many times, you ate breakfast at 9:00 AM. It could have been a habit, a sporadic event, or a one-time occurrence. It could have been yesterday or a year ago or ten years ago. But you have, at some time or another, had breakfast at 9:00 AM.


Regarding the vagueness, the idea is really that (at least in English, but from what you've said possibly in Italian as well) this sentence doesn't mean much of anything. Knowing that you've had breakfast at 9:00 AM at some point in your life, with no further details or context or any idea when this might have happened... It just doesn't tell you very much. It's perfectly comprehensible, but my response would likely be "When?" (that is, at what point in your life or how often did you do this) or "...and?" (that is, "What's the rest of your sentence? What are you trying to say?").


It just doesn't seem to be a useful data point, by itself. I think that's probably the thrust behind StoneyB's comment; you can say it, just without context I'm not sure why you would.




Now that I better understand the context (that eating breakfast at 9:00 is something you were able to do it Italy, but can no longer do, and you are reminiscing) I would add:


In that case I would use could have. Technically it just means that you were able to do it, but in context it means that because you were able to do it, you sometimes did. So try something like:




It was wonderful. I could have breakfast at 9:00 AM, eat a lot of delicious food... I could relax outside in the sun whenever I wanted..."



(Okay, just making up examples here. But you get the idea).


xna - how do I make an enemy target an ally unit?


I have 2 different classes, a EnemyFighter class, and a EnemyBomber class. both are planes that I have that can fly around the map.( i also have AllyFighter, and AllyBomber)


So far they can follow me, and eachother, but how would I set up a target variable or something?


like I could set up a target variable for the enemyfighter


AllyFighter target;

and a variable holding the location of the allyfighter as a Vector2.



but then what if I want to target an AllyBomber? do I have to make 2 variables? or is there some other approach I should take?


Thanks


EDIT: Maybe a better question would be how can I target different enemy types (ones with different classes)? or at least hold there information in a 'target' variable



Answer



Ideally you'd have some parent class that all these classes inherit from. For example, if all of your planes inherited from Plane, then you could easily create a list of those different classes with something like:


List targets = new List();

Now you can add all your targets to the same list. Of course you can just have a single target too:


Plane target;


And then as long as AllyFighter, AllyBomber and so on all extend Plane, you can use the same variable.


Do note that you will only be able to access the data that's commonly stored your targets at the Plane level (apart from casting the object to the correct type). This means you'll want to store the important information for targeting at the Plane level (you likely would anyway since most of the information is going to be common to them all). So stuff like position, health, armor, etc. should be data inside Plane not inside AllyBomber.


software engineering - Throwing Exceptions in C++ game DLL's? Pros and Cons


What are the pros and cons of using Exceptions in C++ in relation to game development.


Google style guide says that they don't use Exceptions for a variety of reasons. Are the same reasons pertinent towards game development?



We do not use C++ exceptions... - google-styleguide.googlecode.com




Some issues to think about.



  • How it pertains to the development of a libraries used through multiple projects.

  • How does it affect unit testing, integration testing, etc?

  • What does it do to using third party libraries.



Answer



There are also some nasty consequences for using exceptions in C++ if you don't know all the details of how they work. Since many games are written in C++ this may be a factor.


For example, in C++ throwing an exception in a destructor can have serious consequences. It can cause all kinds of undefined behavior and crashes, because you can get trapped in a situation where you have more than one active exception in flight. (See Item #8 of Effective C++ for more info on this.)



physics - How do I implement deceleration for the player character?


Using delta time with addition and subtraction is easy.


player.speed += 100 * dt

However, multiplication and division complicate things a bit. For example, let's say I want the player to double his speed every second.


player.speed = player.speed * 2 * dt


I can't do this because it'll slow down the player (unless delta time is really high). Division is the same way, except it'll speed things way up.


How can I handle multiplication and division with delta time?


Edit: it looks like my question has confused everyone. I really just wanted to be able to implement deceleration without this horrible mass of code:


else
if speed > 0 then
speed = speed - 20 * dt
if speed < 0 then
speed = 0
end

end
if speed < 0 then
speed = speed + 20 * dt
if speed > 0 then
speed = 0
end
end
end

Because that's way bigger than it needs to be. So far a better solution seems to be:



speed = speed - speed * whatever_number * dt


past vs present perfect - Have forgotten or forgot?



I'm walking out of a bar and I'm putting my hand in my pocket, and I can't find my wallet.


So it's better to say "I have forgotten my wallet" or "I forgot my wallet" ?




"I'm born and brought up in India" - I don't want to use the 'past' tense here


I read this question here and this one is different because the second clause is in present tense.



I'm born and brought up in India. - too commonly practiced in India.




I was born in India is correct over I'm born in India. I am pretty clear on that, but then if I want to include brought up which is still effective (present), how do I say that?



I was born and brought up in India. - does not relate the sentence to the present time then. As both are in past


I was born in India + I was brought up in India. - no. I AM brought up in India, I'm still here.




Answer



The expression you want is



I was born and raised in India.




Both verbs are completed actions, so they are expressed in the past tense. "Raised" means that you spent your childhood there, and is neutral on the issue of whether you are currently living in India or not. You could also say "brought up" instead, but "born and raised" is a more convenient expression.




Incidentally, a related expression is



I'm Indian, born and bred.



That has a slightly different meaning. To be bred means to be brought up in a specific way, so this sentence means that you have very strong characteristically Indian habits due to being brought up there. This sentence is also neutral on the issue of where you currently reside.


Saturday, March 30, 2019

java - How do I tackle top down RPG movement?


I have a game that I am writing in Java. It is a top down RPG and I am trying to handle movement in the world. The world is largely procedural and I am having a difficult time tackling how to handle character movement around the world and render the changes to the screen. I have the world loaded in blocks which contains all the tiles.


How do I tackle the character movement?



I am stumped and can't figure out where I should go with it.


EDIT: Well I was abstract with the issue at hand.


Right now I can only think of rigidly sticking everything into a 2D array and saving the block ID and the player offset in the Block or I could just "float" everything and move about between tiles so to speak.



Answer



Use World Coordinates


(Or as you put it, float everything.)


World coordinates are what you generally work with, and there's plenty of reasons for that. They're the most simple and intuitive way of representing your position in the world, and the only way of really comparing the positions of any two entities in the same world.


You gain nothing but work by having him be tracked within individual blocks. Well, one advantage is you get to determine which block he's in, but you can already calculate that with world coordinates.




The rest of this answer will be an explanation of how to calculate the world block a player is in based on his world coordinates.



I'll write the code snippet as if you have a 2D vector class named Vector2 - the kind of vector you find in geometry, not the Vector list type offered by java.util. If you don't have any geometric Vector classes, you should find some online or write some yourself (anyone know any quality geometry libraries for Java?)


The Vector2 class will have an X field and a Y field, which are public numbers (doesn't matter which numeric type here).


// Current player X,Y position in the world
Player.Position.X, Player.Position.Y

// An array of map blocks with consistent width and height
Block[x][y] blocks = World.GetBlocks();

// We'll wing it with an example global width/height for all blocks
Block.GetWidth() == 100;

Block.GetHeight() == 100;

// To ensure we're on the same page:
// blocks[0][0] should be at position (0,0) in the world.
// blocks[2][5] should be at position (200,500) due to the width/height of a block.

// Also:
// Assuming (0,0) is in the top-left of the game world, the origin of a block
// is its top-left point. That means the point (200,500) is at the top-left of
// blocks[2][5] (as oppose to, say, its center).


public Vector2 GetPlayersBlockPosition() {
Vector2 blockPosition = new Vector2();
blockPosition.X = (int)(Player.Position.X / Block.GetWidth());
blockPosition.Y = (int)(Player.Position.Y / Block.GetHeight());

return blockPosition;
}

public Block GetPlayersBlock() {

Vector2 bp = GetPlayersBlockPosition();
return blocks[bp.X, bp.Y];
}

Block block = GetPlayersBlock();

2 functions > all the mess of within-block tracking and inter-block transferring


No intellisense with with Unity 5.5, Visual Studio Code integration, OSX 10.12.1


I get this with the listed software. It doesn't recognize object types and I can't use reference-finding. I have the Omnisharp plugin installed and updated. Just wondering if this is supposed to work properly yet. I'm opening it with Assets->Open Project In Code.


enter image description here



Answer



In the .csproj file, there's this:



/Applications/Unity 5.5.0f3/Unity.app/Contents/Managed/UnityEngine.dll


Note the space in the file path. Changing Unity's location to



/Applications/Unity5.5.0f3


then deleting the generated .sln and .csproj files fixed it.


animation - Ledge grab and climb in Unity3D


I just started on a new project. In this project one of the main gameplay mechanics is that you can grab a ledge on certain points in a level and hang on to it.


Now my question, since I've been wrestling with this for quite a while now. How could I actually implement this? I have tried it with animations, but it's just really ugly since the player will snap to a certain point where the animation starts.




grammaticality - Why no subject after “as”?




  1. Please correct me, but does as function as a conjunction here? I already tried i, ii, and iii.



Page 3: In any event it might be said that Hart ‘won’ the debate in the sense that it was his infl uence that led to the passing of the 1960s legislation liberalising the law on abortion, prostitution, homosexuality, and abolishing capital punishment. However such issues can still arise – as was seen in the Brown case, considered later, and the ongoing issue of the ‘rights’ relating to assisted suicide...



2. Why no subject here? Isn't the subject such issues, which implies "such issues can still arise – as they were seen in the Brown case..."?



Page 43: ...the new coalition Justice Minister is the extremely experienced MP Kenneth Clarke QC, although his experience may not save the legal system from the consequences of the comprehensive spending review, as was made only too evident in the announcement in November 2010 that the whole of the civil legal aid system was to be fundamentally restructured, not to say cut (see further at chapter 14 below)



(Question 3 has been posted separately) 4. Why no subject here? What'd be the subject?



5. Are there any terms that describe the ideas or issues in this entire post?


Source: The English Legal System 2012-2013, Gary Slapper. I myself bolded and italicised.




relative pronouns - What is the subject of this sentence


I've seen this sentence in someone's facebook status but it sounds unnatural to me.



I'm the Rumplestiltskin who spins straw into gold



I thought it should be spin because the subject is I, but I'm not sure. Which one is the subject in this sentence, I or Rumplestiltskin and why?



Answer



The subject of the main clause is I. But then that subject talks about himself in the third person: The Rumplestiltskin who spins straw into gold. Spins agrees with the subject of the relative clause.



2d - Is there a good way to get pixel-perfect collision detection in XNA?


Is there a well-known way (or perhaps reusable bit of code) for pixel-perfect collision detection in XNA?


I assume this would also use polygons (boxes/triangles/circles) for a first-pass, quick-test for collisions, and if that test indicated a collision, it would then search for a per-pixel collision.


This can be complicated, because we have to account for scale, rotation, and transparency.


WARNING: If you're using the sample code from the link from the answer below, be aware that the scaling of the matrix is commented out for good reason. You don't need to uncomment it out to get scaling to work.



Answer



I see that you tagged the question as 2d, so I'll go ahead and dump my code:


class Sprite {

[...]


public bool CollidesWith(Sprite other)
{
// Default behavior uses per-pixel collision detection
return CollidesWith(other, true);
}

public bool CollidesWith(Sprite other, bool calcPerPixel)
{
// Get dimensions of texture

int widthOther = other.Texture.Width;
int heightOther = other.Texture.Height;
int widthMe = Texture.Width;
int heightMe = Texture.Height;

if ( calcPerPixel && // if we need per pixel
(( Math.Min(widthOther, heightOther) > 100) || // at least avoid doing it
( Math.Min(widthMe, heightMe) > 100))) // for small sizes (nobody will notice :P)
{
return Bounds.Intersects(other.Bounds) // If simple intersection fails, don't even bother with per-pixel

&& PerPixelCollision(this, other);
}

return Bounds.Intersects(other.Bounds);
}

static bool PerPixelCollision(Sprite a, Sprite b)
{
// Get Color data of each Texture
Color[] bitsA = new Color[a.Texture.Width * a.Texture.Height];

a.Texture.GetData(bitsA);
Color[] bitsB = new Color[b.Texture.Width * b.Texture.Height];
b.Texture.GetData(bitsB);

// Calculate the intersecting rectangle
int x1 = Math.Max(a.Bounds.X, b.Bounds.X);
int x2 = Math.Min(a.Bounds.X + a.Bounds.Width, b.Bounds.X + b.Bounds.Width);

int y1 = Math.Max(a.Bounds.Y, b.Bounds.Y);
int y2 = Math.Min(a.Bounds.Y + a.Bounds.Height, b.Bounds.Y + b.Bounds.Height);


// For each single pixel in the intersecting rectangle
for (int y = y1; y < y2; ++y)
{
for (int x = x1; x < x2; ++x)
{
// Get the color from each texture
Color a = bitsA[(x - a.Bounds.X) + (y - a.Bounds.Y)*a.Texture.Width];
Color b = bitsB[(x - b.Bounds.X) + (y - b.Bounds.Y)*b.Texture.Width];


if (a.A != 0 && b.A != 0) // If both colors are not transparent (the alpha channel is not 0), then there is a collision
{
return true;
}
}
}
// If no collision occurred by now, we're clear.
return false;
}


private Rectangle bounds = Rectangle.Empty;
public virtual Rectangle Bounds
{
get
{
return new Rectangle(
(int)Position.X - Texture.Width,
(int)Position.Y - Texture.Height,
Texture.Width,
Texture.Height);

}

}

Edit: While this code is almost self explanatory, I did feel bad for not having comments, so I added some ;) I also got rid of the bitwise operations since it was doing basically what the Color.A property does in a more complicated way ;)


Friday, March 29, 2019

Questions with and without auxiliary


Which one is correct way of asking Questions ? When to ask questions without auxiliary? Is asking question without Auxiliary is more formal way of asking questions ?


a) Are you Ok? b) You ok ?


a) Did you see that movie? b) You saw that movie ?


a) When did you see that movie ? b) When you saw that movie ?


a) Who did give you this? b ) Who gave you this ?




Design of a turn-based game where actions have side-effects


I am writing a computer version of the game Dominion. It is a turn-based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later.


The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine; in general, players pass through an "action phase", a "buy phase", and a "clean-up phase" (in that order). Based on the answer to the question How to implement turn-based game engine?, the state machine is a standard technique for this situation.


My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard-coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn-based Strategy Loop does not go into a level of detail that addresses designs to solve this problem.


What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object/class/whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine.




Answer



I agree with Jari Komppa that defining card effects with a powerful scripting language is the way to go. But I believe that the key to maximum flexibility is scriptable event-handling.


In order to allow cards to interact with later game events, you could add a scripting API to add "script hooks" to certain events, like the beginnings and endings of game phases, or certain actions the players can perform. That means that the script which is executed when a card is played is able to register a function which is called the next time a specific phase is reached. The number of functions which can be registred for each event should be unlimited. When there is more than one, they are then called in their order of registration (unless of course there is a core game rule which says something different).


It should be possible to register these hooks for all players or for certain players only. I would also suggest to add the posibility for hooks to decide for themselves if they should keep being called or not. In these examples the return value of the hook function (true or false) is used to express this.


Your double-turn card would then do something like this:


add_event_hook('cleanup_phase_end', current_player, function {
setNextPlayer(current_player); // make the player take another turn
return false; // unregister this hook afterwards
});


(I have no idea if Dominion even has something like a "cleanup phase" - in this example it's the hypothetical last phase of the players turn)


A card which allows every player to draw an additional card at the beginning of their draw phase would look like this:


add_event_hook('draw_phase_begin', NULL, function {
drawCard(current_player); // draw a card
return true; // keep doing this until the hook is removed explicitely
});

A card which makes the target player lose a hit point whenever they play a card would look like this:


add_event_hook('play_card', target_player, function {
changeHitPoints(target_player, -1); // remove a hit point

return true;
});

You won't get around hard-coding some game actions like drawing cards or losing hit points, because their complete definition - what exactly it means to "draw a card" - is part of the core game mechanics. For example, I know some TCGs where when your have to draw a card for whatever reason and your deck is empty, you lose the game. This rule isn't printed on every card which makes you draw cards, because it's in the rule book. So you shouldn't have to check for that lose condition in every card's script either. Checking things like that should be part of the hard-coded drawCard() function (which, by the way, would also be a good candidate for a hookable event).


By the way: It's unlikely that you will be able to plan ahead for every obscure mechanic future editions could come up with, so no matter what you do, you still will have to add new functionality for future editions once in a while (in this case, a confetti throwing minigame).


marketing - What defines a AAA game?


I tried to find a precise definition. I found clues on Wikipedia and on Gaming SE, but I cannot find more than an approximation like:



Equivalent of blockbuster movie in cinema, an AAA game is a game with highest development budgets and levels of promotion.



The definition seems imprecise. How can I be sure a game is AAA?


Let's imagine a small indie studio making games and growing up. They hire more and more people through the years and invest more and more money in their game. At which milestone would their game be considered as AAA?




Answer



There really isn't a precise metric for being "AAA" or even a solid definition of the term. Generally it means the game in question had a large budget, which usually translates to having a large team and lots of promotional spending. But how large is large? Nobody can really agree (or has really bothered to try), just like nobody agrees on how many concurrent players you need to be a "massively" multiplayer game.


Most people would probably agree that games with budgets in the millions are "AAA," and games with budgets in the thousands aren't. But the middle? Is a hundred thousand dollars an AAA game? What about half-a-million?


If you want to call your game a AAA game, go for it. If you "pull it off" in the sense that your game manages to wow people enough that they don't disagree with that assessment, then I guess you're a AAA game (or similarly, just wait until people start calling your games AAA or calling your studio a AAA studio).


subject verb agreement - The Beatles were/was



The Beatles were an English rock band, formed in Liverpool in 1960.




Source


The Beatles were? Aren't/isn't The Beatles a proper noun and it refers to one group? I don't understand why WikiPedia and other sources use The Beatles were instead of The Beatles was. Is it because of the s? Somebody please explain me about this, it goes against all the rules I've learnt and it is not even in my grammar books.



Answer



Lennon was a Beatle. McCartney was a Beatle. Harrison was a Beatle. Starr was a Beatle. Together, the Beatles formed a band called The Beatles.


In my opinion, English doesn't handle this subtlety particularly well, and mostly conflates "the band" with "the constituents of the band". With "The Beatles", the tendency is to refer to the group of members.


"The Beatles was ..." can work, but only in a context where the listener is strongly expecting the name of an abstract entity. It will sound weird if the context can, at all, be construed as referring to the people.


Thursday, March 28, 2019

meaning in context - Do "twice as high xxxxx as" , "twice as high" and "twice higher" mean the same thing?


What do the following sentences actually mean? Are they the same in meaning?




  1. The cost of living is twice as high in New York as it is in Tokyo.

  2. The cost of living in New York is twice as high in Tokyo.

  3. The cost of living in New York is twice higher than in Tokyo.

  4. The cost of living in New York is two times higher than in Tokyo.




If they have the same meaning, then can I actually use them as a basis for composing other sentences having the same meanings? Such as:



1a. Your child is a hundred times as adorable as your pet dog.
1b. Your child is a hundred times adorable than your pet dog.


2a. Her room is twice as large as mine.
2b. Her room is twice larger than mine.





verb forms - "read and accepted" or "read and accept"?


Is this phrase correct?



By purchasing this product, you certify that you have read and accepted the Privacy Policy and Terms and Conditions...




Is it just me or it feels like "read and accepted" should be "read and accept" only, or is it already grammatically valid?



Answer



The word have in the phrase suggests that the action has already been taken, ie it is in the past. Therefore, the verbs indicate past tense: you have already read (pronounced 'red') and accepted the conditions.


If the have wasn't there, then that clause in the sentence would be saying that you will (but haven't yet) read (pronounced reed) and accept the conditions.


So, the statement is grammatically correct. It deals with tenses a bit awkwardly, but it is valid.


Difference between "this" and "that"



I always use them reversibly since I'm not too sure about their differences.


For instance, in an email I just wrote:




  • solution 1

  • solution 2


Which one of those solutions do you prefer?



I'm not too sure whether I should use these or those. In the above example I used those because it sounds cooler, maybe not the best way to choose...



Also I read that that is used appointing what is far while this is for close things. But in my example are solutions far or close?



Answer




My hometown had a shop where the owner made three kinds of donuts every morning: plain donuts, powdered sugar donuts, and cinnamon donuts. He also had a sign above each tray of donuts; the signs read THEM, THESE, and THOSE.


During the day, customers would make requests, such as, "I'd like two cinnamon donuts, and a plain donut," and whoever was behind the counter would put those in a bag. But if the shop owner happened to be behind the corner – mind you, this man was known for being a little eccentric – he would look at you as if he didn't understand, and say something like, "Look, we have Them, These, and Those – now what can I get for ya?" whereby the customer would have to say, "I'll take one of Them, and two of Those."


I always marveled at the way, no matter what combination of donuts you were ordering, you could still create a grammatically correct sentence using his names for the donuts, such as, "I'd like three of them, one of these, and two of those."



My point for relating this story is that sometimes these words (those words?) can be used interchangeably, with little or no change in meaning.


I'd say that, in the general case, these seems to imply closer proximity then those (as in, "These marbles [in my hand] look very pretty, but those marbles [behind the counter] don't look as nice.") However, as the donut example illustrates, even this generality doesn't always hold true.


Back to your example: I think you could have used either these or those, and, much like at the donut counter, either word would work just fine.



xna - How to get mouse position relative to the map?


I'm creating a game in XNA similar to Minecraft - Minecraft 2D


It looks like this



game


Here's how it works:




  • All blocks are generated once with fixed x,y coordinates and just re-drawn.


        //generate world
    for (int i = 0; i < 25; i++)
    {
    blocks.Add(new Block("top", i * 32, 32 * 7, Color.White));
    for (int j = 8; j < 20; j++)

    {
    blocks.Add(new Block("dirt", i * 32, 32 * j, Color.White));
    }
    }


  • When user clicks on a block, I just browse through all blocks and check whether block exists.


    if ((mouseCoordinate.X - (mouseCoordinate.X % 32)) == block.x && (mouseCoordinate.Y - (mouseCoordinate.Y % 32)) == block.y) {
    //destroy block
    }



  • Currently, without any camera movements, everything works. When I move my camera just about 32px to the right, for example, it's all broken. I can't do previous step anymore.



  • What I need: I need to get mouse position relative to the map, not to the game window. How can I get mouse position relative to the map? Basically, I want mouse position 0,0 on the point I have circled here


00


How do I calculate it?


EDIT: here's my camera class (yes, Matrix)


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Reflection;
namespace MojePrvniHra

{
public class Camera2d
{
protected float _zoom; // Camera Zoom
public Matrix _transform; // Matrix Transform
public Vector2 _pos; // Camera Position
protected float _rotation; // Camera Rotation

public Camera2d()
{

_zoom = 1.0f;
_rotation = 0.0f;
_pos = Vector2.Zero;
}// Sets and gets zoom
public float Zoom
{
get { return _zoom; }
set { _zoom = value; if (_zoom < 0.1f) _zoom = 0.1f; } // Negative zoom will flip image
}


public float Rotation
{
get { return _rotation; }
set { _rotation = value; }
}

// Auxiliary function to move the camera
public void Move(Vector2 amount)
{
_pos += amount;

}
// Get set position
public Vector2 Pos
{
get { return _pos; }
set { _pos = value; }
}

public Matrix get_transformation(GraphicsDevice graphicsDevice)
{

_transform =
Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
Matrix.CreateRotationZ(_rotation) *
Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
Matrix.CreateTranslation(new Vector3(graphicsDevice.Viewport.Width * 0.5f, graphicsDevice.Viewport.Height * 0.5f, 0));
return _transform;
}

}
}


and here's how I start my spriteBatch


       spriteBatch.Begin(SpriteSortMode.BackToFront,
BlendState.AlphaBlend,
null,
null,
null,
null,
cam.get_transformation(graphics.GraphicsDevice));

Answer




Solution


Is your camera simulated using a view matrix? If so, all you need to do is:


Vector2 worldPosition = Vector2.Transform(mousePosition, Matrix.Invert(viewMatrix));

And if you're not using a view matrix... you should :-)


Explanation


The view matrix transforms coordinates from world space into view space. The inverse of this matrix does the opposite - it transforms coordinates from view space back into world space.


Since your mouse coordinates are defined in view space, all you need to do is transform them with the inverse view matrix to convert them into world space.


terminology - “Hope (this or it) helps?



Just wondering what's more appropriate, after reading this conversation


It's "Hope it helps" correct? or better "Hope this helps"? Practically, is better to use it or this?


Or it may depend if we are in USA, UK or Australia?




c# - How can I draw a line of certain length and direction?


I want to create a line of certain length and direction.


What I mean by this is drawing a line from Point A to Point B. Normally in Unity C# to draw a line from Point A to Point B is simply:


Debug.DrawLine(point_A, point_B);

The diagram would be something like this



A----------------B

But I dont want something like this, I want it to draw from Point A to Point B but with a certain length. So I am guessing I need the direction for this to work. But I don't know how to code it.


Here is a basic diagram of how i want it.


A--------        B


sentence construction - What part of speech is Christmas in "who were Christmas shopping"



It was therefore a full week later - once they had surreptitiously obtained hairs from innocent Muggles who were Christmas shopping, and had practiced Apparating and Disapparating while underneath the Invisibility Cloak together - that Hermione agreed to make the journey.


Harry Potter and the Deathly Hallows



What's the grammar point for "who were Christmas shopping" then? It looks like Christmas is an adverb to modify the verb shopping, but Christmas is only a noun according to this dictionary. How should we understand the grammar here?



Answer



In fact, Christmas is acting as an adverb modifying the verb shopping, which is in present particle form (gerund- meaning it is an ongoing action) it is just like saying:




He was shopping for Christmas, i.e: he was buying things for Christmas.



Other examples for such constructions are:



He was break dancing - he was dancing in break style.



Wednesday, March 27, 2019

xna - Generating 'Specially' shaped rooms for a Dungeon


I've made a fairly simple dungeon generator but now I want to expand on it so that I can procedurally generate a dungeon with irregular shaped rooms. I don't just want any old crazy shapes popping up though, I want to be able to have room types that follow a certain pattern but ultimately have random sizes. I just don't have a clue how to generate rooms that aren't just square.


I have an idea of how to merge squares together to make rooms comprised of other rooms, but I'm more interested in how to get hexagon and octagon shaped rooms, or doughnut-like rooms. My code for generating square rooms is:


    public static char[,] GetSquareRoom(int width, int height)
{
char[,] roomLayout_Square;

roomLayout_Square = new char[width, height];

for (int x = 0; x < roomLayout_Square.GetLength(0); x++)

for (int y = 0; y < roomLayout_Square.GetLength(1); y++)
if (x == 0 || y == 0 || x == width - 1 || y == height - 1)
roomLayout_Square[x, y] = '#';
else
roomLayout_Square[x, y] = '.';

return roomLayout_Square;
}

I would like to create more functions like this that will accept a few variables so I can create specific variations of these room-types, so I can input specific number and randomly generated values alike.



:)



Answer



You can create a room that is in the shape of a regular convex polygon with arbitrary sides, size and rotation.
Steps:



  1. Draw walls by picking pairs of points around a circle and linearly interpolating between them. The number of pairs should equal the number of sides of the shape. You will need to use trig for this.

  2. Create a floor by filling the shape using some sort of fill algorithm.


You can then create a doughnut shaped room by subtracting a smaller generated room from the center of a larger generated room. You should keep the walls of the smaller generated room though.


Since I found this interesting I went ahead and tried implementing it myself. I would recommend not looking at my code until you have tried to write it yourself though.



public static char[,] RegConvexPolyRoom(int sides, double radius, double rotation)
{
// convert the rotation degrees to radians.
rotation *= Math.PI / 180.0;

// make an array size that is sure to fit the room.
int roomSize = (int) Math.Ceiling(radius*2) + 1;

char[,] room = new char[roomSize, roomSize];


// first we must create the walls of the room.
double rchange = (Math.PI * 2.0) / sides;
for (double r = 0; r < Math.PI * 2; r += rchange)
{
// define first point.
double p1_x = radius + Math.Cos(r + rotation) * radius;
double p1_y = radius + Math.Sin(r + rotation) * radius;

// define second point (rotated 1 iteration further).
double p2_x = radius + Math.Cos(r + rotation + rchange) * radius;

double p2_y = radius + Math.Sin(r + rotation + rchange) * radius;

// get distance between the two points.
double len = Math.Sqrt(Math.Pow(p2_x - p1_x, 2) + Math.Pow(p2_y - p1_y, 2));

// linearly interpolate between the two points and place walls between them.
for (double i = 0; i < 1; i += 1.0 / len)
{
int place_x = (int) Math.Round((1 - i) * p1_x + i * p2_x);
int place_y = (int) Math.Round((1 - i) * p1_y + i * p2_y);


room[place_y, place_x] = '#';
}
}

// now we have to fill the room with a floor.
// this is done using something similar to a scanline algorithm.
for (int scan = 0; scan < roomSize; scan++)
{
int left_x = -1;

int right_x = -1;
bool spaceDetected = false;

for (int i = 0; i < roomSize; i++)
{
if (room[scan, i] == '#')
{
if (!spaceDetected)
left_x = i;
else

{
right_x = i;
break;
}
}
else if (left_x != -1)
spaceDetected = true;
}

if (right_x != -1)

{
for (int i = left_x + 1; i < right_x; i++)
{
room[scan, i] = '.';
}
}
}

return room;
}


Here is a hexagonal room generated with the above method:


     ##############
#.............#
#..............#
#...............#
#................#
#.................#
#...................#
##...................#

#.....................#
#.......................#
#.......................#
#.......................#
#.....................#
#...................##
#..................#
#.................#
#...............##
#...............#

#..............#
#.............#
##############

word usage - Choosing between up and above in this context?


I have always been confused about the use of above and up. Lets say I in grocery store and I am supposed to describe the position of X in a high rack.



Should I say "It is 3 shelves up and in the back/front (of that shelf)." or "It is 5 shelves above and in the front."?


Can anyone please explain to me which is correct and why?



Answer



I think you could say



It is 3 rows up and in the back/front.



although there should be some reference as to up from where, unless you are looking at that row. You could say



It is 3 rows up from the middle shelf, and in the back/front.




In the case of



It is 5 rows above and in the front.



you have to specify above what. In this case you would not use above by itself. You could say



It is 5 rows above the vanilla ice cream and in the front.



Also, in a grocery store, it is more likely to say shelves rather than rows.



Tuesday, March 26, 2019

input - How do I simulate the mouse and keyboard using C# or C++?


I want to start develop for Kinect, but hardest theme for it - how to send keyboard and mouse input to any application. In previous question I got an advice to develop my own driver for this devices, but this will take a while.


I imagine application like a gate, that can translate SendMessage's into system wide input or driver application with API to send this inputs. So I wonder, is there are drivers or simulators that can interact with C# or C++?


Small edition: SendMessage, PostMessage, keybd_event will work only on Windows application with common messages loop. So I need driver application that will work on low, kernel, level.




networking - Tips for communication between JS browser game and node.js server?




I am tinkering around with some simple Canvas based cave flyer game and I would like to make it multiplayer eventually. The plan is to use Node.js on the server side.


The data sent over would consists of position of each player, direction, velocity and such. The player movements are simple force physics, so I should be able to extrapolate movements before next update from server.


Any tips or best practices on the communications side? I guess web sockets are the way to go. Should I send information in every pass of the game loop or with specified intervals? Also, I don't mind if it doesn't work with older browsers.



Answer



I recently made a asteroids/geometry wars crossover with Node.js / JavaScript:
http://github.com/BonsaiDen/NodeGame-Shooter


It has a fat Server which processes the game and thin clients which are basically just views. The client does some interpolation and things to make it look smooth.


You may want to look at these two files, which contain the underlying networking logic, as well as the actor and client models:
http://github.com/BonsaiDen/NodeGame-Shooter/blob/master/client/nodegame.client.js
http://github.com/BonsaiDen/NodeGame-Shooter/blob/master/server/nodegame.js



The whole game is based on Actors which handle their "update events"(the stuff that gets send to the clients) on their own, for the most part. It's also possible to hide actors from specific client to implement, for example, invisibility.


One can also record games and just feed the messages into the client to play them back.


As far as the tech goes:
WebSockets are the way to go here. I also did a custom binary encoding for JS that, while giving up on things like more than 2 decimal places on floats, is about 50% smaller than JSON(and is 2x as fast under V8 than native JSON encoding)


meaning in context - What does the phrase 'a punch above your weight' in the sentence ''Get a punch above your weight mug for your mother-in-law Helena''mean?


What does the phrase 'a punch above your weight' in the sentence ''Get a punch above your weight mug for your mother-in-law Helena''mean?



I have found in Urban Dictionary the following:



to punch above your weight means 'to pull or pick up someone who's better looking than you'.



After Urban Dictionary gives examples. One of these is the following:



Get a punch above your weight mug for your mother-in-law Helena.



What does the phrase 'a punch above your weight' mean in this example?




unity - Can't use one variable to store different data types. What's a better solution?



I'm trying to make my first game in Unity and I decided to have a go at making a 3D tower defence. I've created a UI Panel with 4 buttons used to upgrade the turrets. When the player selects a turret the panel appears and the button text and images are changed to match the type of turret selected. The buttons all call one function 'UpgradeButtonClick(int upgradeIndex)' which applies the upgrade to the selected turret.


In order to reuse a single panel and one set of buttons I created a class called 'Turret' which will be attached to every type of turret. This class stores the cost, materials and upgrades for the turret as well as a reference to the attack script for the turret. This was fine until I introduced a second type of turret (I.e. lazer turrets and fire turrets). Originally I had:


public LazerTurretShooting attackScript;

But that will obviously not work for the fire turret. Ideally I would like to test the type of turret and then declare the correct variable type. But I can't as the variable would then only be accessible where it is declared and not to the whole class.


The attackScript variable is used near the bottom of the UpgradeButtonClick function to modify the turrets damageMultiplier and apply the upgradeEffect. See below:


public class TurretManager : MonoBehaviour {

/* Removed unnecessary functions */


public void UpgradeButtonClick(int upgradeIndex)
{

Turret turret = selectedTurret.GetComponentInParent(); //Get the Turret script from the selected turret

if (turret.turretUpgrades.Length > upgradeIndex) //Make sure there is an upgrade with the selected index
{

if (!turret.turretUpgrades[upgradeIndex].applied) //Check if this upgrade has already been applied
{

bool applyUpgrade = false;
int prerequisiteIndex;

//Check if the upgrade requires a previous upgrade to be applied first
prerequisiteIndex = turret.turretUpgrades[upgradeIndex].requiredUpgrade; //Store the index of the required upgrade/prerequisite
if (prerequisiteIndex > -1)
{

if (turret.turretUpgrades[prerequisiteIndex].applied) //If the required upgrade/prerequisite has already been applied
{ //Allow the upgrade

applyUpgrade = true;
} else
{ //Don't allow the upgrade
applyUpgrade = false;
}

} else
{ //There was no prerequisite so allow the upgrade
applyUpgrade = true;
}


if (applyUpgrade)
{
if (ScoreManager.Instance.Money > turret.turretUpgrades[upgradeIndex].upgradeCost) //Check if the player has enough money to buy the upgrade
{
turret.attackScript.damageMultiplier += turret.turretUpgrades[upgradeIndex].damageMultiplier; //Apply the new damage multiplyer
turret.turretUpgrades[upgradeIndex].applied = true; //Set the applied flag so this upgrade cannot be applied twice
UpdateUpgradePanelButtons(); //Update the buttons to enable buttons for any upgrades which require this upgrade as a prerequisite

ScoreManager.Instance.Money -= turret.turretUpgrades[upgradeIndex].upgradeCost; //Charge the player for the upgrade


if (turret.turretUpgrades[upgradeIndex].applyUpgradeEffect) //If the upgrade enables the turrets additional effect, turn it on
{
turret.attackScript.applyUpgradeEffect = true;
}

}

}


}

}

}

}

Here is the full Turret class:


[System.Serializable]

public struct TurretUpgrade
{
[Tooltip ("The damage multiplier is increased additively. So to increase damage by 20% enter 0.2 or to decrease enter -0.2")]
public float damageMultiplier;
[Tooltip("Tells the turret to play its additional effect (E.g. Dual Lazers on a lazer turret)")]
public bool applyUpgradeEffect;
[Tooltip ("Index of upgrade required before this upgrade can be applied. (-1 = none required)")]
public int requiredUpgrade;
[HideInInspector]
public bool applied; //Has the upgrade been applied to this turret

[Tooltip ("Text to display under the upgrade button (E.g. '10% Damage Increase')")]
public string upgradeButtonText;
[Tooltip ("The cost of the upgrade")]
public int upgradeCost;
[Tooltip ("A Sprite image for the upgrade button")]
public Sprite buttonSprite;

}

public class Turret : MonoBehaviour {

public Material opaqueMaterial;
public Material translucentMaterial;
public int cost;
public LazerTurretShooting attackScript; //This variable would need to store different types

public TurretUpgrade[] turretUpgrades = new TurretUpgrade[4];

void Awake()
{
//I need to get the correct type of script for this turret

attackScript = GetComponent();
//attackScript = GetComponent();
//attackScript = GetComponent();
}
}

What would be the best way to approach this? If I create separate 'Turret' classes (E.g. LazerTurret and FireTurret) the function which sets the text and images of the upgrade buttons wouldn't work because it usees:


Turret turret = selectedTurret.GetComponentInParent();
for (...) //Loops all 4 buttons
textLabels[0].text = turret.turretUpgrades[i].upgradeButtonText;

//etc

I can provide this full function if its needed.



Answer



Like @PompeyPaul says, Polymorphism is key. To expand on the idea, here is another possible design for a Turret class:


public abstract class Turret : Monobehavior {
...
public abstract void Attack();
public abstract void Upgrade();
}


Assuming that everything besides how the turrets attack and are upgraded is the same for every type, this would expose a common interface for all turrets. Now you could make different specific turret classes:


public class LaserTurret : Turret {
public int statSpecificToLasers = 5;
public void Attack() {
//do something cool with a laser
}
public void Upgrade() {
//Apply changes to statSpecificToLasers
}

}

public class FireTurret : Turret {
public int statSpecificToFire = 12;
public void Attack() {
//do something cool with fire
}
public void Upgrade() {
//Apply changes to statSpecificToFire
}

}

Because the Turret class has virtual methods, you can't really have a concrete Turret, so it cannot be constructed, and you wouldn't attach it to any GamEObjects, but since both LaserTurret and FireTurret inherit from Turret, both can be treated as if they were Turrets. Now, in your TurretManager, selectedTurret can still be declared as a Turret type, but you can pass in either a FireTurret or a LaserTurret. Which Attack() or Upgrade() method gets called depends on which type you pass.


Turret selectedTurret = ob1.GetComponent();
selectedTurret.Attack(); //shoots fire
selectedTurret = ob2.GetComponent();
selectedTurret.Attack(); //shoots a laser

//You can even put them in the same collection
List turrets = new List();

turrets.Add(ob1.GetComponent());
turrets.Add(ob2.GetComponent());

grammar - Is even a preposition/conjunction?



No one can do it , even him.



I've always thought that "even" can function as both preposition and conjunction in that it can be followed by noun phrases or dependent clauses. But dictionaries only say it's an adverb ? And for my example above, what exactly do you call the boldface text in relation to the clause (adverbial...)?




Monday, March 25, 2019

adjectives - What is the difference between "respective" and "corresponding"



Before you begin please connect your laptop's power adapter and an Ethernet cable to their respective outlets.



I found this sentence on Northwestern University's website. Every time I find this type of usage of "respective", I am confused why "respective" is used and think "corresponding" is more suitable. That is, Longman dictionary defines "respective" as follows:



used before a plural noun to refer to the different things that belong to each separate person or thing mentioned



  1. We all went back to our respective homes.


  2. the respective roles of teachers and students



So, I think "respective" is used to describe the relationship "of" not "for". In my example, the outlets for the adapter and the cable, not the outlets of the adapter and the cable.


Is my understanding correct?



Answer



What definition of "corresponding" are you using that makes you believe that it is a better choice than respective?


To me "correspondence" is a relationship between things that are similar, as in the example sentence from the Merriam Webster definition:



"Robert" is a boy's name, and the corresponding name for a girl is "Roberta."




I'm talking about a direct relationship between two names which are the same type of thing. I use "respective" when there are several separate things where I don't want to list out each relationship. For example,



Other horsebreeders' associations, all doing useful work in the interests of their respective breeds, are the Suffolk Horse Society, the Clydesdale Horse Society, the Yorkshire Coach Horse Society, the Cleveland Bay Horse Society, the Polo Pony Society, the Shetland Pony Stud Book Society, the Welsh Pony and Cob Society and the New Forest Pony Association. (*)



The sentence above talks about a relationship of two separate things: an association to a breed of horse.


Here is another example where you would use "corresponding" and not "respective":



One color at a time, twist the fixture wire to the corresponding color outlet wire and replace the wire nut. (*)




Here is another example where you would use "respective" and not "corresponding":



After the party, each student returned to their respective dormitory.



Meaning and usage of ain't


Sometimes I encounter ain't, but I really don't know how to translate it properly.


What does ain't stand for? If I really wanted to use it, in which contexts would you say it's acceptable using it?



Answer



Ain’t is a negative present-tense form of the verbs be and have employed in all persons and numbers:


I ain't           we ain't
you ain't you ain't
he/she/it ain't they ain't


It represents a coalescence of the ordinary spoken contractions of not and the three relevant forms of the two verbs:


am not    ⊲   a’n’t  )  
are not ⊲ a’n’t )
is not ⊲ i’n’t ) ⊲ e’n’t/ha’n’t ⊲ orthographic ain’t/hain't
have not ⊲ ha’n’t )
has not ⊲ ha’n’t )

It is used wherever be not is used: as a copula, in progressive constructions, and in passives; and where have not is used as an auxiliary, in perfect constructions.


Ain’t is not slang (which means, roughly, a fairly novel usage employed by an ‘in-group’ as a token of their ‘in-ness’) but a colloquialism which was at one time used virtually universally. You find it very often in 18th- and 19th-century plays and novels, in the mouths of persons of high social standing.


However, it aroused particular hostility among 19th century schoolmarms, who assaulted it ruthlessly and succeeded in painting it as the mark of illiterate speech. Accordingly, it should not be used in formal contexts except as an ironic nod to the vernacular. It is still very common in speech, but regarded as sub-standard rather than merely non-standard.



mathematics - Elliptical orbit modeling


I'm playing with orbits in a simple 2-d game where a ship flies around in space and is attracted to massive things. The ship's velocity is stored in a vector and acceleration is applied to it every frame as appropriate given Newton's law of universal gravitation. The point masses don't move (there's only 1 right now) so I would expect an elliptical orbit.



Instead, I see this:


This is what I see


I've tried with nearly circular orbits, and I've tried making the masses vastly different (a factor of a million) but I always get this rotated orbit.


Here's some (D) code, for context:


void accelerate(Vector delta)
{
velocity = velocity + delta; // Velocity is a member of the ship class.
}

// This function is called every frame with the fixed mass. It's a

// method of the ship's.
void fall(Well well)
{
// f=(m1 * m2)/(r**2)
// a=f/m
// Ship mass is 1, so a = f.
float mass = 1;
Vector delta = well.position - loc;
float rSquared = delta.magSquared;
float force = well.mass/rSquared;

accelerate(delta * force * mass);
}

Answer



The bug is in the fall function. We have



  1. delta: a vector from the well to the ship

  2. force: the magnitude of the gravity between these two bodies.


|force| is G * m1 * m2 / r^2


but |delta| is already r! so you are actually accelerating too fast. You need to divide by r again (basically normalizing the delta vector) before calling accelerate.



accelerate(delta * well.mass * mass / rSquared / Math.sqrt(rSquared))

word request - Plastic part on the tip of a shoelace


What is the common English name for that "plastic part on the tip of a shoelace" which helps to easily insert the lace into the shoelace holes? (I'm not sure that's the correct name).


Edit: There are also metal parts of the kind.



Answer



It's called an "aglet".




a metal or plastic tag or sheath at the end of a lace used for tying, as of a shoelace.



I've known and used this term for years but whether it can be considered "commonly known" is up for debate. It's certainly not unheard of.


Sunday, March 24, 2019

Present Simple or Present Continuous with "these days"


enter image description here


"These days" express the period around now. Then, I wonder, why is used the Present Simple in the following sentence?:



  • These days I travel a lot. I’m spending more and more time away from home. (Considering the rule given above, I would say: These days I am travelling a lot.)


I've also come across the sentence where both tenses are considered correct:




  • These days, more and more people prefer / are preferring to retire early.


So, is it optional whether we use present simple or continuous with "these days"?



Answer



The present simple can also refer to things in the period around 'now'.


It can be used for statements of general truth ("the sky is blue") or for conditions that pertain ("I know how to change a lightbulb"). When used with an adverbial of time, they might also be used for statements of general truth ("in the morning, I prefer not to speak to people") and provide for a condition as part of that statement. However, an adverbial of time can also accompany a statement of current conditions ("right now, I am hungry"), provided that the adverbial of time involved includes 'now'.


The progressive aspect refers to ongoing or recurring actions, and so can also be used for things that are located in time around now. "I am travelling a lot these days" is essentially equivalent to "I travel a lot these days". A key point that must be understood about English is that there is not always only one verb form/tense/mood/aspect that is correct.


Preferring is a somewhat special case, though. It is rarely used in the progressive aspect. Indeed, I'm racking my brain for cases of use of the -ing form at all, and mostly it's used in various adverbials.




"They were offered the choice of pinot noir or pinot grigio. Preferring red wine, Susan chose the pinot noir."



(I'm not actually sure if it's being a gerund or a participle in that case)


xna - 2D lighting theory: day-and-night cycle, spot lights at night



I am writing a rogue-like 'zombie' management game. The game map will be similar to Prison Architect. A top-down 50 X 50 grid.


I want to implemented a day night cycle and during the night I would like the player to be able to position lights.


I would like to be able to lighten and dark to whole map to display the day and night cycle.


Then lights would be a circle of light blocked by game entities such as walls, players, trees etc.


How would I achieve and what is the standard way of achieving this?



Answer



Sorry for posting a collection of links but your problem has many possible solutions! :)


Various gridbased lighting algorithms traditionally used by roguelikes: http://roguebasin.roguelikedevelopment.org/index.php?title=Category:LOS http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision


A solution I developed to support partial occlusion of grid cells: http://blog.pixelpracht.net/?p=340


Rather complicated pixel-perfect approach that calculates the Field of View as a Polygon: http://www.redblobgames.com/articles/visibility/



A game I wrote a while ago using a similar math based approach: http://runehunt.pixelpracht.net/


Projecting each face outwards, kinda what Carmack did in Doom3 but in 2d space. Causes a lot of overdraw which doesn't matter so much if you have access to hardware acceleration. http://forums.tigsource.com/index.php?topic=8803.0


difference - Want a look vs. want to have a look



  1. I want a look (at sth)

  2. I want to have a look (at sth)


I would think both of the sentences above have negligible nuances. But option 2 seems to be more common (according to google ngram) despite being longer to say. Why is that the case?


Also:




  1. I want a closer look...

  2. I want to have a closer look...


Seem to be much more comparable in popularity, with 3 having more entries than 4. Can this be attributed to difference in degrees of formality?



Answer



The word "look" is typically a verb: in its infinitive form, it is "to look".


I want you TO LOOK at me.


But in your sentences, "a look" is acting as a noun phrase. It encapsulates more than just the act of looking. Instead, it actually deemphasizes the act of only seeing, and instead suggests an opportunity to interact.


"I want a look that problem when you're done."


Experiment! Say, "I want to look out loud" 5 times fast.



You'll hear that it could be heard as, "I want A look", because the "to" and the "a" (I hear it often as "I wan-tahl-ook".) Think French Liaisons. The "want to" requires a distinct double "t", and "want a" only has a single "t". If one is not precise about the enunciation, the difference in phonetics can become blurred.


So, the solution to this is to add a separator between the "want" and the "to". When the emphasis is on "to look", the phrase "to have" will be added so that you can clearly hear the "t" in "to".


When it's focusing on the "opportunity", "want" can be immediately followed by "to" (that is, "I want to look"). But this pattern will sound as if the individual is saying " I want a look" regardless of whether they mean a look or "to look")


This speech pattern will echo itself in writing, and thus we have the distinction between 1 and 2, with 2 being the clearer indication of the "a look" phrasing.


3 and 4 don't have that same issue, so there should be less of a discrepancy between them.


It is clear that 3 is Sub. V. Do. " I want a look" with "closer modifying look, but removing the ambiguity of the phrasing. Example 4 just ends up being less efficient.


Saturday, March 23, 2019

xna - Tile map collision is not working properly


I am having problems setting collision between my sprite and the tiles. I have only done the code for colision for moving upwards but some places on the map it moves up and some places it doesn't.


Here is what I have so far:


Vector2 position;
private static float scalingFactor = 32;

static int tileWidth = 32;
static int tileHeight = 32;


int[ , ] map = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },

{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, },

};

// This is in turtle.update


if ( keyboardState.IsKeyDown( Keys.Up ) )
{
if ( position.Y > screenHeight / 4 )
{
//// current position of the turtle on the tiles
int mapX = ( int )( position.X / scalingFactor );
int mapY = ( int )( position.Y / scalingFactor ) - 1;


if ( isMovable( mapX , mapY , map ) )
{
position.Y = position.Y - scalingFactor;
}
}
else
{
MoveUp();
}

}

private void MoveUp()
{
motion.Y = -1;
}

public bool isMovable( int mapX , int mapY , int[ , ] map )
{
if ( mapX < 0 || mapX > 19 || mapY < 0 || mapY > 20 )

{
return false;
}
int tile = map[ mapX , mapY ];
if ( tile == 0 )
{
return false;
}

return true;

}

protected override void Update( GameTime gameTime )
{
turtle.Update( screenHeight , scalingFactor , map );
base.Update( gameTime );
}

EDIT: What i have tried to do is get the postion of my sprite and over which tile it is, then check whether the next tile is a path or a wall.



Answer




No problem with being new to game development. You just need to make sure to provide enough information so that we can properly help you. Your on the right track with your code and it looks like your isMoveable() function is sound. I'm not sure what the difference between motion.Y and position.y are and why you're setting one vs the other depending on position.Y > screenHeight / 4, so the following maybe isn't what you want to achieve. However, I would suggest this simple structure for moving your character around.


// current position of the turtle on the tiles
int mapX = (int)(position.X / scalingFactor);
int mapY = (int)(position.Y / scalingFactor);
if (keyboardState.IsKeyDown(Keys.Up))
{
if (isMovable(mapX, mapY-1, map))
{
position.Y = position.Y - scalingFactor;
}

} else if (keyboardState.IsKeyDown(Keys.Down))
{
if (isMovable(mapX, mapY+1, map))
{
position.Y = position.Y + scalingFactor;
}
} else if (keyboardState.IsKeyDown(Keys.Right))
{
if (isMovable(mapX+1, mapY, map))
{

position.X = position.X + scalingFactor;
}
} else if (keyboardState.IsKeyDown(Keys.Left))
{
if (isMovable(mapX-1, mapY, map))
{
position.X = position.X - scalingFactor;
}
}


EDIT


This could be because of the way you're indexing into the map. Note orientation for your map as defined in code is not the way it will display on screen. You're indexing into it like this:


int tile = map[ mapX , mapY ];

So mapX is referencing the rows of your array and mapY is referencing the columns. So the top row of tiles on your screen from left to right are referencing the last column in your array from top to bottom.


architecture - Alternatives to Singletons / globals


I've heard countless times about the pitfalls of Singletons / globals, and I understand why they're so often frowned upon.


What I don't understand is what the elegant, non-messy alternative is. It seems that the alternative to using Singletons/globals always involves passing objects a million levels down through your engine objects until they reach the objects that need them.


For example, in my game, I preload some assets when the game starts up. These assets aren't used until much later when the player navigates through the main menu and enters the game. Am I supposed to pass this data from my Game object, to my ScreenManager object (despite the fact that only one Screen actually cares about this data), then to the appropriate Screen object, and anywhere else?


It just seems that I'm trading global state data for cluttered dependency injection, passing data to objects that don't even care about the data except for the purpose of passing it on to child objects.


Is this a case where a Singleton would be a good thing, or is there some elegant solution I'm missing?




Answer



Don't conflate singletons and globals. While some kind of global variables are usually necessary, the singleton is not just a replacement for a global variable, but primarily a way to work around problems of static initialization order in C++ (and FQA). (In other languages, it's a way to work around different language deficiencies, like the lack of global variables and bare functions.)


If you can just use a global pointer instead of a singleton, and make sure it's initialized (manually) before anything needs it, you avoid the function call and branch overhead, the lame syntax to get at the object, and you can actually make a second instance of the class when you need to for tests or because your design changed.


For the few global variables you want (common examples being audio output, list of open windows, keyboard handler, etc.), I recommend the service locator pattern. It makes it easy to replace things with different implementations (e.g. real vs. null audio device), and collects all your globals into one structure to avoid polluting your namespace.


mathematics - Accurately simulating the lots of dice rolls without loops?


OK so if your game rolls lots of dice you can just call a random number generator in a loop. But for any set of dice being rolled often enough you will get a distribution curve/histogram. So my question is there a nice simple calculation I can run that will give me a number that fits that distribution?


E.g. 2D6 - Score - % Probability


2 - 2.77%


3 - 5.55%


4 - 8.33%



5 - 11.11%


6 - 13.88%


7 - 16.66%


8 - 13.88%


9 - 11.11%


10 - 8.33%


11 - 5.55%


12 - 2.77%


So knowing the above you could roll a single d100 and work out an accurate 2D6 value. But once we start with 10D6, 50D6, 100D6, 1000D6 this could save a lot of processing time. So there must be a tutorial / method / algorithm that can do this fast? It is probably handy for stock markets, casinos, strategy games, dwarf fortress etc. What if you could simulate the outcomes of complete strategic battle that would take hours to play with a few calls to this function and some basic maths?




Friday, March 22, 2019

java - What is a good file format for saving game data?




I need to save some custom game data. Map, player, etc.


All of them will have "sub objects". For example, a map and map will have an "array" of tiles. ie, hierarchical data. Hopefully nothing binary.


What would be a good format for these?



So far I'ved considered:


Serailization: This is FAST and easy, but tends to break when I change the underlying classes :(


XML: I really hate parsing this. My test case was over 100+ lines of code and seemed likes tons of "busy work" for even a very simple format.


INI: would be really clumsy for hierarchical data.


Protobuf: Never used it, but read you have to do a lot of manual mucking around and breaks if you change the class.


Other options? That's why I'm here!


Edit: this is Java btw.


Edit 2:


I settled on "Controlled Binary Serialization" (see below).


Pros:





  • it's fast




  • it's small (on disk) and can be easily compressed/decompressed during read/write.




  • it's super easy to read/write from game and toolset.





  • I can decide what to include/exclude of the object.




  • Objects/Data can be nested.




Cons:





  • Can't edit it by hand (like XML, YAML, etc)




  • Can't easily read/modify it with scripts




  • Java Serialization by default is pretty slow/bloated compared to other implentations, but it's stable and works





Answer




To display hierachical data, YAML or JSON would be good options. They are far simpler and easier to parse than XML.


Another option would be a "controlled" binary serialization process. Every object writes it's state out in a controlled way, i.e.


void player::save(savegame &sgm)
{
sgm.write(this->position);
sgm.write(other properties);
inventory.save(sgm);
}

id Tech 4 (Quake 4 / Doom 3 engine) uses such an approach.



graphics - Transformations between coordinate systems


In a graphics engine, I have three three-dimensional orthogonal coordinate systems, O, A and B.


A and B are the result of two different transformations from O. I now want to calculate the transformation matrix R, which takes you from A to B. R should be the rotation and translation with respect to coordinate system A, not the original coordinate system O.


Which of the following is correct?


(1) B = A * R or (2) B = R * A


By doing some simple worked examples, it seems that (1) is correct. However, my intuition says that (2) is correct, because the transformation to A should be applied before the transformation to B, via R. Which is it?


Thanks :)





3D Illusion of a 2D Planet Texture


Several years ago I overheard a technique that gives the user the illusion of a rotating planet by using a 2D texture. Given that the user isn't able to change its position or viewport.


What's the name of this technique?



Answer



OK I think I have the rep now. Contents of previous post with images embedded. Is this the rotating planet effect you're looking for? Its simply a scrolling 2D image viewed through a semi-transparent "hole" in the star field.


I put together a quick little animated gif of what the effect would look like. Clearly it could be animated a lot smoother - I shifted the planet surface by 4 pixels each frame. It's also not set to wrap the image so there's a glitch at the end of the loop.



planet http://www.perludus.com/orbit.gif


I did do this all in Photoshop, but the concept should work in a 2D rendering environment that lets you do alpha transparencies, etc. Here are a series of screenshots showing the process...



  1. Create a blank star background, and cut a round hole in it.
    alt text

  2. Find a grayscale shaded sphere for your planet, like this one
    alt text

  3. Here is our stars with hole and the shaded sphere on top, semi transparent
    alt text

  4. Make a blue circle the size of the hole, and give it an outer blue glow. Also set it to be semi-transparent. Here's what it looks like with the shaded sphere

    alt text

  5. Now find a planet surface texture. I found this one just googling "planet surface texture"
    alt text

  6. Place the planet texture UNDER the star image with the semi-transparent hole in it to get this look
    alt text


To animate your planet's surface, just move the underlying planet surface texture. You'll have to get clever about shifting the texture when it reaches the edge to get a seamless and endless rotation.


Hope this helps and is the effect you were looking for!


PS Saw this article about artists with a rather novel way to create planet textures - made me think of this answer :) http://www.behance.net/gallery/Pan-Planets/9557465


Thursday, March 21, 2019

negation - My final question about until / by


I think in the sentences below, “by” doesn't work and the only proper preposition is “until”, because all of these sentences are negative where “by” doesn't make any sense at all.



-A- She won’t be back until 5 o’clock.
-B- He will not return until Monday.
-C- Why didn't you come until 12 o’clock?
-D- I won’t be ready until Tuesday.
-E- I can’t be ready until 8 p.m.

-F- You mustn't be at home until 7 o’clock.



Whereas If we change the negative forms of these sentences to positive, we will see that "by" would be the proper preposition and then "until" would not work. Am I right?




unity - How can I find the distance from bezier curve anchor points to control points for a circle approximation and their positions



From the image below, I have represented a circle by a closed bezier curve made of two cubic bezier segments. I am aware that a bezier curve cannot represent a perfect circle. How can I calculate the distance from the anchor points to the control points based on the distance from both anchor points to give a close approximation of a circle?


Also how can I use the calculated distance to find the positions for the control points?


enter image description here



Answer



Please don't forget to search for existing information on your problem area before posting new questions - especially when you're asking about something fundamental that's surely been answered before.


That said, I'd like to take a different approach than the answers I linked above.


These past answers seem to choose their control points so that the midpoint of the Bézier curve lies at the midpoint of the circular arc. That means that the half-curve on either side of the midpoint bulge out beyond the circle.


That's not bad, but we can do better, in terms of minimizing the maximum error. If we undershoot a little at the midpoint, we reduce the overshoot on either side, keeping our Bézier curve closer to the circle overall.


To do this, instead of kissing the arc at \$t = \frac 1 2\$, we'll cross it at \$t = \frac 1 3\$ and \$t = \frac 2 3\$. Our curve will weave back-and-forth across the circle we want to follow instead of staying strictly outside it.


I'll spare you the full derivation, but to do that, we want our control handles to have the following length:



$$l = \frac {3\sqrt{\sin^2\theta - 70 \cos \theta + 70} - 17 \sin \theta}{15 - 12 \cos \theta} \cdot r $$


Where \$\theta\$ is the angle of the circular arc (180° or \$\pi\$ radians if you use just two anchor points at opposite ends of the diameter), and \$r\$ is the radius of the circle (half the distance between the anchor points if they're at opposite ends of a diameter)


For the 180° case that translates to \$l = \frac {2 \sqrt {35}} 9 \cdot r \approx 1.314684396 \cdot r \$, with a maximum error of about 1.40%


(For comparison, the answers linked above use \$l = \frac 4 3 \cdot r \approx 1.333333 \cdot r\$ which suffers an error of about 1.83%)


If you care about fidelity, I'd strongly recommend using more than two segments to represent the circle. Even just 3 segments brings the error down to 0.12%, 4 segments brings it to 0.02%


If your Bézier anchor point is at \$A_i = (c_x + r \cdot \cos {\alpha}, c_y + r \cdot \sin \alpha)\$, with \$(c_x, c_y)\$ the center of the circle, and \$\alpha\$ the angle of the point counter-clockwise from the positive x-axis, then its corresponding anchor point is at \$C_i = A_i \pm l \cdot (-\sin \alpha, \cos \alpha)\$, with the sign of the \$\pm\$ being + for the start point, and - for the end.




Here's an animation of this method in action:


Animation showing Bézier curves wrapping around a circle


And here's the code I used:



// OnValidate is called by the editor automatically when the user modifies 
// the inspector parameters like center, radius, and circleCoverageDegrees.
// Here it's used to update our array of Bézier control points.
private void OnValidate() {
BezierCircle(center, radius, circleCoverageDegrees, 0, bezierPoints, 0);
BezierCircle(center, radius, 0, -circleCoverageDegrees, bezierPoints, 3);
}

// This method populates 4 cubic Bézier control points into an array,
// so that the resulting curve approximates a circular arc.

static void BezierCircle(
Vector2 center, float radius,
float startAngleDegrees, float endAngleDegrees,
Vector2[] points, int startIndex
) {
// First, compute how long our tangents should be to best fit this arc.
float angle = Mathf.Abs(endAngleDegrees - startAngleDegrees) * Mathf.Deg2Rad;
float sine = Mathf.Sin(angle);
float cosine = Mathf.Cos(angle);
float tangentScale = radius * (3 * Mathf.Sqrt(sine * sine - 70f * cosine + 70) - 17 * sine) / (15 - 12 * cosine);

tangentScale *= Mathf.Sign(endAngleDegrees - startAngleDegrees);

// Place the start anchor point and its control point relative to it.
angle = Mathf.Deg2Rad * startAngleDegrees;
sine = Mathf.Sin(angle);
cosine = Mathf.Cos(angle);

points[startIndex] = center + radius * new Vector2(cosine, sine);
points[startIndex + 1] = points[startIndex] + tangentScale * new Vector2(-sine, cosine);


// Place the end anchor point and its control point relative to it.
angle = Mathf.Deg2Rad * endAngleDegrees;
sine = Mathf.Sin(angle);
cosine = Mathf.Cos(angle);

points[startIndex + 3] = center + radius * new Vector2(cosine, sine);
points[startIndex + 2] = points[startIndex + 3] - tangentScale * new Vector2(-sine, cosine);
}

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