How do I clone an object then pick a random position, then draw it.
This is the code I have for the object:
public class Trash : ICloneable
{
private Texture2D _texture;
private float _rotation;
public Vector2 Position;
public Vector2 Origin;
public float RotationVelocity = 3f;
public float LinearVelocity = 4f;
public Trash(Texture2D texture)
{
_texture = texture;
}
public void Update()
{
// Do epic stuff here
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(_texture, Position, null, Color.White, _rotation, Origin, 1, SpriteEffects.None, 0f);
}
public object Clone()
{
return this.MemberwiseClone();
}
And this is code I have in Game1.cs so far:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private SeaJam.Objects.Trash Trash;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
var texture = Content.Load<Texture2D>("Prototype");
Trash = new Objects.Trash(texture)
{
Position = new Vector2(100, 100),
Origin = new Vector2(texture.Width / 2, texture.Height - 25),
};
}
protected override void Update(GameTime gameTime)
{
Trash.Update();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
Trash.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
private void AddTrash()
{
var rnd = new System.Random();
var NewTrash = Trash.Clone();
}
The problem is Whenever I'd try to give a random position for the clone in the AddTrash() Method, I'd only get errors, such as "'object' does not contain a definition for 'Position' and no accessible extension method 'Position' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)"
your constructor:
public Trash(Texture2D texture)
{
_texture = texture;
}
Needs to be extended with the desired changeable parameters. In your case, it needs to add Position and Origin as parameter, and then apply it as a value.
Like this:
public Trash(Texture2D texture, Vector2 position, Vector2 origin)
{
_texture = texture;
Position = position;
Origin = origin;
}
And change the way you call it in the game1.cs as well, they need to work similair like texture:
var texture = Content.Load<Texture2D>("Prototype");
var position = new Vector2(100, 100),
var origin = new Vector2(texture.Width / 2, texture.Height - 25),
Trash = new Objects.Trash(texture, position, origin);
And as a tip: keep consistency in your field names, mixing in underscore and lowercase in one field, and uppercase in an other field will get confusing to understand. especially when the parameters needs a name different from the fields as well. I prefer to keep them all with the first letter uppercase.
Related
I'm using XNA to create a Space Invaders copy. So I'm animating many sprites with the same logic placed in their own class, but using different values for most vars. Here is my way of animating from spritesheets:
Texture2D playerTex;
Vector2 playerPos = new Vector2(x, y), playerOrigin;
Rectangle playerHitBox;
float animationTimer = 0f, animationInterval = 100f;
int currentFrame = 1, frameWidth = example number, frameHeight = example number 2;
public void LoadContent(ContentManager Content)
{
playerTex = Content.Load<Texture2D>("ship");
}
public void Update(GameTime gameTime)
{
playerHitBox = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
playerOrigin = new Vector2(playerHitBox.X / 2, playerHitBox.Y / 2);
animationTimer += (float)gameTime.ElapsedGameTime.Milliseconds;
if (animationTimer > animationInterval)
{
currentFrame++;
animationTimer = 0f;
}
if (currentFrame == 2)
{
currentFrame = 0;
}
playerHitBox = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
playerOrigin = new Vector2(playerHitBox.Width / 2, playerHitBox.Height / 2);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(playerTex, playerPos, playerHitBox, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);
}
Instead of using this logic for every animating object within its own class I'm looking for a way to create a sprite class anduse inheritance to Update()/Draw() the sprite. Could something like this be a good approach for the Draw() method?
public void Draw(Texture2D spriteTex, Vector2 spritePos, Nullable<Rectangle> spriteSourceRect, Color spriteColor, Single spriteRotation, Vector2 spriteOrigin, Vector2 spriteScale, SpriteEffects spriteEffects, Single spriteLayerDepth, SpriteBatch spriteBatch)
{
if (spriteTex != null)
{
spriteBatch.Draw(spriteTex, spritePos, spriteSourceRect, spriteColor, spriteRotation, spriteOrigin, spriteScale, spriteEffects, spriteLayerDepth);
}
}
You can:
Create Sprite class to keep common animation properties like texture, duration and current index.
Create Invider class for custom data like position, health and other.
Create a collection to store custom data for each object in game class.
For example:
class Sprite
{
public Texture2D texture;
public Rectangle Frame;
private frameIndex;
private frameCount;
private frameDuration;
private frameInterval;
public Sprite(Texture pTexture, ...)
{
// init sprite data
}
public Update(GameTime pGameTime)
{
// update sprite data
}
}
class Invider
{
private Sprite Sprite;
public Vector2 Porision;
public int Health;
public Invider(Sprite pSprite, Vector2 pPosition)
{
this.Sprite = pSprite;
this.Position = pPosition;
}
public void Update(GameTime pGameTime)
{
// update invider data
}
public void Draw(SpriteBatch pSpriteBatch)
{
pSpriteBatch.Draw(this.Sprite.Texture, this.Sprite.Frame, this.Position, Color.White);
}
}
public class Game1 : Game
{
private SpriteBatch spriteBatch;
private Dictionary<int, Invider> invidersByID;
private Sprite inviderSprite;
public override Initialize()
{
// fill inviderByID collection
}
public override LoadData()
{
// create inviderSprite
}
public static UpdateStatic(GameTime pGameTime)
{
// update static data like frame index
}
public override void Update(GameTime pGameTime)
{
this.inviderSprite.Update(pGameTime);
foreach(Invider invider in invidersByID.Values){
{
invider.Update(pGameTime);
}
}
public override Draw(SpriteBatch pSpriteBatch)
{
this.spriteBatch.Begin();
foreach(Invider invider in invidersByID.Values){
{
invider.Update(pGameTime);
}
this.spriteBatch.End();
}
}
The game stopped working when the following function is called:
The error is: shotmanager object wont be passed and always will be null! I was following a tutorial and did exactly as he did!
I clearly initiated it.
Some coding here
namespace SpaceShip
{
class Enemy: Sprite
{
public shotmanager shotmanager;
private double timesincelastshot;
private const int timedelay = 1;
private Vector2 pos;
public Enemy(Texture2D Text, Vector2 VEC, Rectangle REC, shotmanager shotmanager)
: base(Text, VEC, REC)
{
shipspeed = 300;
this.shotmanager = shotmanager;
}
public override void Update(KeyboardState keyboard, GameTime gameTime)
{
var random = new Random();
if (Velocity == Vector2.Zero)
{
var direction = random.Next(2);
Velocity = new Vector2(direction == 0 ? -1 : 1, 0);
}
else if (gameTime.ElapsedGameTime.Seconds % 2 == 0)
{
if (random.Next(15) == 0)
Velocity = new Vector2(-velocity.X, velocity.Y);
}
timesincelastshot += gameTime.ElapsedGameTime.TotalSeconds;
if (timesincelastshot > timedelay)
{
if (random.Next(2) == 0)
pos = calculateposition();
shotmanager.fireenemyshot(pos);
timesincelastshot = 0;
}
base.Update(keyboard, gameTime);
}
private Vector2 calculateposition()
{
return VEC + new Vector2(TEXT.Width/2, TEXT.Height/2);
}
}
}
namespace SpaceShip
{
public class shotmanager
{
private Shot shot;
public Texture2D shottexture;
private Rectangle bounds;
private List<Shot> shotgroup = new List<Shot>();
//public shooting shot;
Vector2 vec;
public shotmanager(Texture2D shottexture, Rectangle bounds)
{
// TODO: Complete member initialization
this.shottexture = shottexture;
this.bounds = bounds;
}
public void fireenemyshot(Vector2 shotposition)
{
var inflatebounds = bounds;
vec = shotposition;
inflatebounds.Inflate(10, 10);
shot.Velocity = new Vector2(0, 1);
shotgroup.Add(shot);
shot = new Shot(shottexture, shotposition, inflatebounds);
}
public void draw(SpriteBatch spriteBatch)
{
foreach (var i in shotgroup)
shot.draw(spriteBatch);
}
public void Update(KeyboardState keyboard, GameTime gameTime)
{
foreach (var i in shotgroup)
shot.Update(keyboard, gameTime);
}
}
}
namespace SpaceShip
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Sprite background;
shipclass spaceship;
//Sprite spaceship;
SpriteFont score;
EnemyManger enemy;
Texture2D shottexture;
public shotmanager shotmanager;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
var alienship = Content.Load<Texture2D>("flying_saucer_2");
Texture2D spaceshiptexture;
spriteBatch = new SpriteBatch(GraphicsDevice);
spaceshiptexture = Content.Load<Texture2D>("1358114942_kspaceduel");
var positionx = (graphics.GraphicsDevice.Viewport.Width - spaceshiptexture.Width) / 2;
var positiony = (graphics.GraphicsDevice.Viewport.Height - spaceshiptexture.Height );
var ship = new Rectangle(0, graphics.GraphicsDevice.Viewport.Height - spaceshiptexture.Height -150 , graphics.GraphicsDevice.Viewport.Width, spaceshiptexture.Height+150);
background = new Sprite(Content.Load<Texture2D>("large_space_1920x1200"), Vector2.Zero, graphics.GraphicsDevice.Viewport.Bounds);
spaceship = new shipclass(spaceshiptexture, new Vector2(positionx, positiony), ship);
score = Content.Load<SpriteFont>("SpriteFont1");
shottexture = Content.Load<Texture2D>("64px-SpaceInvadersLaserDepiction");
shotmanager = new shotmanager(shottexture, graphics.GraphicsDevice.Viewport.Bounds);
enemy = new EnemyManger(alienship, graphics.GraphicsDevice.Viewport.Bounds, shotmanager);
public void fireenemyshot(Vector2 shotposition)
{
var inflatebounds = bounds;
vec = shotposition;
inflatebounds.Inflate(10, 10);
// CULPRIT HERE
shot.Velocity = new Vector2(0, 1);
shotgroup.Add(shot);
// THIS IS DONE TOO LATE.
shot = new Shot(shottexture, shotposition, inflatebounds);
}
The problem is that you are attempting to set the Velocity on shot, but you have never instantiated it before here. You are instantiating it after you are attempting to use.
EDIT - FYI The pos that you are passing into this method from Enemy is also never set. It's a struct so it should be initialized, however, you are never giving it a value. Nevermind, I saw where it gets set.
I am trying to make Pong in XNA/C# using a class for the Paddle and Ball
Game1.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Pong
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Paddle Paddle1 = new Paddle();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
Paddle1.Draw();
base.Draw(gameTime);
}
}
}
Paddle.cs:
namespace Pong
{
class Paddle
{
SpriteBatch spriteBatch;
ContentManager Content;
Texture2D paddle1;
Texture2D paddle2;
Vector2 Paddle1;
Vector2 Paddle2;
public void LoadContent()
{
paddle1 = Content.Load<Texture2D>("pongpaddle1");
Paddle1 = new Vector2();
Paddle1.X = 50;
Paddle1.Y = 50;
}
public void Draw()
{
spriteBatch.Begin(); //Causes NullReferenceException was unhandled, Object reference not set to an instance of an object.
spriteBatch.Draw(paddle1, Paddle1, Color.White);
spriteBatch.End();
}
}
}
I don't have anything in the Ball class yet, but it will use similar methods to Paddle.cs
Every time I've ran the code, I keep getting a System.StackOverFlow exception whenever it hits this line of code in Game1.cs:
Paddle Paddle1 = new Paddle();
How do I fix this? I don't see how it's run out of memory already.
EDIT: Updated code.
What's happening here is that Paddle inherits Game1. Game1 creates new Paddles:
Paddle Paddle1 = new Paddle();
Paddle Paddle2 = new Paddle();
Those Paddles are Games that need to initialize their own set of Paddles. Infinite recursion! I'm not sure how XNA works, but if that's how the inheritance should be, just move your initializations to Initialize():
// TODO: Add your initialization logic here
base.Initialize();
this.Paddle1 = new Paddle();
this.Paddle2 = new Paddle();
I kind of doubt that a game object should inherit from the game itself, though. That would seem like a rather poor design decision.
public class Game1 : Microsoft.Xna.Framework.Game
{
Paddle Paddle1 = new Paddle();
Paddle Paddle2 = new Paddle();
...
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
Paddle1.LoadContent();
}
...
}
class Paddle : Game1
{
...
protected override void LoadContent()
{
Paddle1 = new Vector2();
Paddle1.X = 50;
Paddle1.Y = 50;
base.LoadContent();
}
...
}
Two big problems here, there is a recursive LoadContent call. Not to mention your paddles have paddles which have paddles... Why is your paddle inheriting from Game1? It almost definitely shouldn't be.
Also your paddle instances instantiate other paddle instances, so you're in a loop of instantiating other paddle classes.
It seems like you might want to take a step back and just get used to some basic code first? For what it's worth, I wrote pong in xna for fun a few years back, it's a bit messy, but it might give you some starting help.
Here is an example of a paddle class based off the DrawableGameComponent class (drawn in primatives so it's a bit verbose):
public class Paddle : DrawableGameComponent
{
private readonly VertexPositionColor[] _vertices = new VertexPositionColor[6];
private readonly float _width;
private readonly float _height;
private IndexBuffer _indexbuffer;
private VertexBuffer _vertexbuffer;
public Vector3 Position { get; set; }
public Vector3 Direction { get; set; }
public float Speed { get; set; }
public Paddle(Game game, float width, float height)
: base(game)
{
_width = width;
_height = height;
}
protected override void LoadContent()
{
base.LoadContent();
_vertices[0].Position = new Vector3(0, 0, 0);
_vertices[0].Color = Color.Red;
_vertices[1].Position = new Vector3(_width, _height, 0);
_vertices[1].Color = Color.Green;
_vertices[2].Position = new Vector3(0, _height, 0);
_vertices[2].Color = Color.Blue;
_vertices[3].Position = new Vector3(_width, 0, 0);
_vertices[3].Color = Color.Green;
_vertexbuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), _vertices.Length, BufferUsage.WriteOnly);
_vertexbuffer.SetData(_vertices);
var indices = new short[6];
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 3;
indices[5] = 1;
_indexbuffer = new IndexBuffer(GraphicsDevice, typeof(short), 6, BufferUsage.WriteOnly);
_indexbuffer.SetData(indices);
}
public BoundingBox GetBoundingBox()
{
return new BoundingBox(Position, Position + new Vector3(_width, _height, 0));
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
GraphicsDevice.SetVertexBuffer(_vertexbuffer);
GraphicsDevice.Indices = _indexbuffer;
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);
}
}
I have problem. I have tryed how to make my texture move, but my solution is slow and it is not working. Does anybody know how to make texture2D move using C# XNAGamestudio. ANybody please help me!
EDIT:
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Hashtable Objects = new Hashtable();
public Hashtable XPOS = new Hashtable();
public Hashtable YPOS = new Hashtable();
public int NUM = 0;
public bool UP = true;
public bool DOWN = false;
public bool LEFT = false;
public bool RIGHT = false;
......
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
this.AddObject("Nameee", "C:\\Box.png");
// TODO: Add your update logic here
if (UP)
{
if (NUM != 25)
{
AppendObject(new Vector2((float)this.XPOS["Nameee"], (float)this.XPOS["Nameee"] - NUM), "Nameee");
NUM++;
Thread.Sleep(100);
}
else
UP = false;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
//GraphicsDevice.Clear(Color.CornflowerBlue);
//spriteBatch.Begin();
//spriteBatch.End();
//base.Draw(gameTime);
}
public void AddObject(string TagName, string ObjectImage)
{
Texture2D fileTexture;
using (FileStream fileStream = new FileStream(#ObjectImage, FileMode.Open))
{
fileTexture = Texture2D.FromStream(graphics.GraphicsDevice, fileStream);
}
if (!this.Objects.ContainsKey(TagName))
{
this.Objects.Add(TagName, fileTexture);
this.XPOS.Add(TagName, 0.0F);
this.YPOS.Add(TagName, 50.0F);
}
}
public void AppendObject(Vector2 pos, string tagName)
{
spriteBatch.Begin();
spriteBatch.Draw((Texture2D)this.Objects[tagName], new Vector2((float)this.XPOS[tagName], (float)this.YPOS[tagName]), Color.White);
spriteBatch.End();
}
Hmm, well technically, this looks like it should move a texture along the X axis.
As for performance, you may want to take these things into consideration:
You are calling this.AddObject("Nameee", "C:\\Box.png"); on every update. That's not a good thing. Call this once in your LoadContent() method.
Instead of using Thread.Sleep(100);, I would suggest tracking the time elapsed with GameTime. (Hit the comment if you need an example of how to do this)
You are creating a new vector2 on each pass for the texture position. While this probably doesn't have a noticeable performance hit since its only creating 10 a second (thanks to your Thread.Sleep(100);, I would suggest using the same one.
On a side note, I would recommend completely refactoring this code for a more object oriented approach. Create a class that holds a Texture2D and a Vector2. Then give it an Update() method and a Draw(SpriteBatch sb) method and perform your work in there.
That's just a suggestion though.
You can do something similar to this, and you should use the content manager to load assets.
public class Sprite
{
public Vector2 Position = Vector2.Zero;
public Texture2D Texture;
public float Scale = 1;
public void LoadAsset(Game game, string asset)
{
Texture = game.Content.Load<Texture2d>(asset);
}
public Draw(SpriteBatch batch)
{
batch.Draw(Texture, Position, null, Color.White, ...,... Scale,...);
}
}
//In your game:
List<Sprite> Sprites = new List<Sprite>();
Initialize()
{
base.Initialize();
Sprite myBox = new Box();
myBox.LoadAsset("Box");
Sprites.Add(myBox);
}
Update(GameTime gametime)
{
myBox.Position += Vector2.UnitX * Speed * (float) gametime.elapsed.TotalSeconds;
}
Draw()
{
batch.begin();
foreach (Sprite sprite in Sprites) sprite.Draw(batch);
batch.end();
}
Both good answers by Blau and justnS. I would also advise to take a look at some XNA tutorials to get a better understanding of the XNA Framework and how it should be used (i.e. the purpose of the separate Initialize(), LoadContent(), Update(), Draw(), etc methods).
Try these for starters:
Riemer's
MSDN
XNA Game Dev
this is my code so far:
Game1.cs Class:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player MyPlayer;
Texture2D Ball;
int GraphicsWidth,GraphicsHeight;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
GraphicsWidth = graphics.PreferredBackBufferWidth;
GraphicsHeight= graphics.PreferredBackBufferHeight;
MyPlayer = new Player(Ball, new Vector2(100, 100), Vector2.Zero);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Ball = Content.Load<Texture2D>("Images/ball");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
MyPlayer.Draw(spriteBatch);
base.Draw(gameTime);
}
}
Player class(The ball):
class Player
{
Texture2D Texture;
Vector2 Positon,Velocity;
public int Height
{
get { return this.Texture.Height; }
}
public int Width
{
get { return this.Texture.Width; }
}
public Player(Texture2D tex, Vector2 position,Vector2 velocity)
{
this.Texture = tex;
this.Positon = position;
this.Velocity = velocity;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(Texture, Positon, Color.White);
spriteBatch.End();
}
}
When I try to debug the game I have the following error:
This method does not accept null for this parameter.
Parameter name: texture
In that part:
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(Texture, Positon, Color.White);
spriteBatch.End();
}
Btw, I'd like to ask if I can make this code better or something like that.
Thanks alot!
Looks like you create the Player object before you've loaded the Ball content, and thus, the player holds null instead of a texture, but the Ball field in the Game is the real texture.
I would move the creation of Player into LoadContent, after you've assigned the Ball.
Ball = Content.Load<Texture2D>("Images/ball");
MyPlayer = new Player(Ball, new Vector2(100, 100), Vector2.Zero);
I'm going to preface my answer by saying you should call spriteBatch.begin() and spriteBatch.end() in your Game1.cs Draw function instead of your Player.cs Draw function. It's expensive and you shouldn't do it more than once per draw frame, unless it's absolutely necessary (it's not in this case).
With regards to your actual question, you need to load your player in the LoadContent method rather than your Initialize method.
Initialize is happening before your texture is loaded.
try moving MyPlayer = new Player(Ball, new Vector2(100, 100), Vector2.Zero);
into your LoadContent method after you load the texture into Ball.
It looks like you're loading the ball texture after you've already initialized myPlayer with the "NULL" Ball texture
This is because Initialize is called before LoadContent, and at the point you create your Player the Ball texture is still null.
Either create the Player object in LoadContent, after you load the ball, or allow Player to load its own content.