Hello everyone,
I started to implement a basic physics engine in my game, and I just want someone to look at my code and see if I did it right. I think I did, but it never hurts to have someone look at it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using Engine.ContentManger;
namespace TestEngine.CollitionDetection
{
class MovingObject
{
GraphicsDeviceManager Graphics;
Texture2D Texture;
Vector2 Position, Size, Velocity, Acceleration;
float Speed, Resistance;
Rectangle Rec;
KeyboardState keyboardState;
public MovingObject()
{
Position = Vector2.Zero;
Size = new Vector2(32, 32);
}
public void Initialize(GraphicsDeviceManager Graphics)
{
this.Graphics = Graphics;
}
public void LoadContent()
{
Texture = StreamTexture.LoadTextureFromStream(Graphics, "Content/test.png");
}
public void Update(GameTime gameTime)
{
Speed = 0.0005f * (float)gameTime.ElapsedGameTime.TotalMilliseconds;
Resistance = 0.0001f * (float)gameTime.ElapsedGameTime.TotalMilliseconds;;
keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.W))
Acceleration.Y -= Speed;
else if (Acceleration.Y < 0)
Acceleration.Y += Resistance;
if (keyboardState.IsKeyDown(Keys.S))
Acceleration.Y += Speed;
else if (Acceleration.Y > 0)
Acceleration.Y -= Resistance;
if (keyboardState.IsKeyDown(Keys.D))
Acceleration.X += Speed;
else if (Acceleration.X > 0)
Acceleration.X -= Resistance;
if (keyboardState.IsKeyDown(Keys.A))
Acceleration.X -= Speed;
else if (Acceleration.X < 0)
Acceleration.X += Resistance;
Velocity += Acceleration;
Rec = new Rectangle((int)(Position.X + Velocity.X), (int)(Position.Y + Velocity.Y), (int)Size.X, (int)Size.Y);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Rec, Color.White);
}
}
}
*Short back story about me and physics in high school, not impotent to read *
I always had trouble with physics in high school and I never understood it very well. So I decided to make my own physics engine in my game and I think I'm doing well. After reading some articles about physics 101 and watching some videos on Youtube, I started to fall in love with physics and I started to wonder why I had such a hard time understanding physics in high school. I guess I didn't have the option to implement basic physics in a game and tinker with the variables and see how they moved and reacted in high school.