here’s my code for the player class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace My_Game.Content.Sprites
{
internal class Player : Sprites
{
public Player() {
setDefaultVariables();
}
public Player(ContentManager content)
{
loadTexture(content);
}
private void setDefaultVariables() {
position.X = Global.WIDTH / 2 - 8;
position.Y = Global.HEIGHT / 2 - 8;
color = Color.White;
speed = 200;
}
private void loadTexture(ContentManager content)
{
texture = content.Load<Texture2D>("Gold Idle");
}
public void update(GameTime gameTime)
{
var kstate = Keyboard.GetState();
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
//moving the player
if (kstate.IsKeyDown(Keys.W))
{
position.Y -= speed * deltaTime;
}
if (kstate.IsKeyDown(Keys.S))
{
position.Y += speed * deltaTime;
}
if (kstate.IsKeyDown(Keys.A))
{
position.X -= speed * deltaTime;
}
if (kstate.IsKeyDown(Keys.D))
{
position.X += speed * deltaTime;
}
//collsisions with side of screen
if (position.X <= 0)
{
position.X = 0;
}
if (position.X >= Global.WIDTH - texture.Width)
{
position.X = Global.WIDTH - texture.Width;
}
if (position.Y <= 0)
{
position.Y = 0;
}
if (position.Y >= Global.HEIGHT - texture.Height)
{
position.Y = Global.HEIGHT - texture.Height;
}
}
}
}
For some reason the texture is set to null when I call it in the collisions section.
I put the first player constructor in the Game1 class, and I put the other in the LoadContent function.