Thanks, I ended up figuring it out in another way, but yours is waaay cleaner. I just found it hard because I first couldn't use Vector2, but then I found out you can split it into the players x and y, but then I tried inputing the Rectangle (player.center.x, player.center, 0, 0), and it wasn't working. Now that I look at both codes, i realize I was missing the "new". Do you mind explaining why it's needed?
Code:
int first = (int)player.Center.X + (player.direction * 20) + (int)(player.velocity.X * 10);
int second = (int)player.Center.Y + 40 + (int)(player.velocity.Y * 10);
Rectangle rectangle1 = new Rectangle(first, second, 0, 0);
Random rand = new Random();
int d4 = rand.Next(1, 5); // creates a number between 1 and 4
CombatText.NewText(rectangle1, color1, d4, false, false);
Muuuuuch cleaner
Code:
CombatText.NewText(new Rectangle((int)player.Center.X + (player.direction * 20) + (int)(player.velocity.X * 10), (int)player.Center.Y + 40 + (int)(player.velocity.Y * 10),0,0), new Color(151, 107, 75), d4, false, false);
Well, it's actually a bit confusing, but the
new
keyword works differently for things of type
struct
and things of type
object
. When using the
new
keyword, it is only ever placed before a call to the type's constructor (a special function called when defining/creating an instance). Constructors themselves are always named the same thing as their type and are always preceded with the
new
keyword (as far as I know).
- When using "new" for a
struct
's constructor, an instance of the
struct
is returned.
- When using "new" for an
object
's constructor, a (managed) pointer to a newly "malloced" instance of the type of the object is returned.
"Rectangle" is a
struct
, which means that when you do
Rectangle myRect = new Rectangle(64, 96, 8, 8)
, you are making a an instance of a "Rectangle" and storing/copying it to the variable named "myRect". In the case of
CombatText.NewText()
, you are using the
new
keyword to make a new "Rectangle" that is being passed directly to the function. Storing this in a variable and then passing the variable will have the exact same result, but with extra steps.
If you have a variable who's type is a
struct
(like one of type "Rectangle") and you want to define it but don't need the constructor, you can do:
Rectangle myRect = default(Rectangle)
. This will set all values/fields the
struct
is composed of to their default. The difference between using
default
and using
new
is that using
default
does not actually make a new instance of the
struct
, but instead, directly sets the values of the variable itself (remember,
new
makes a new instance of the struct from the constructor which is then
copied when other things are assigned to it). It's also important to note that since the
default
keyword just modifies a variable, trying to use it as a function argument will result in the compiler: creating an extra local variable, defining it with
default
, then passing this variable as the argument.