Created
February 22, 2012 15:09
-
-
Save poemdexter/1885471 to your computer and use it in GitHub Desktop.
Physics for Goons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using Microsoft.Xna.Framework; | |
using Microsoft.Xna.Framework.Input; | |
namespace Mastiff | |
{ | |
class Physics | |
{ | |
public Vector2 Position { get; set; } | |
public Vector2 PrevPosition { get; set; } | |
public Vector2 Velocity { get; set; } | |
public float Acceleration { get; set; } | |
public float MaxSpeed { get; set; } | |
public float DeltaTime { get; set; } | |
public Physics() | |
{ | |
Acceleration = 0.2f; // our rate of acceleration | |
Velocity = Vector2.Zero; // our starting velocity | |
MaxSpeed = 8.0f; // can't go faster than this | |
Position = new Vector2(100, 100); // let's start here | |
} | |
public void ApplyPhysics(GameTime gameTime, KeyboardState keyboardState) | |
{ | |
DeltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; | |
if (keyboardState.IsKeyDown(Keys.Right)) | |
Accelerate(1); | |
else if (keyboardState.IsKeyDown(Keys.Left)) | |
Accelerate(-1); | |
else | |
Decelerate(); | |
Move(); | |
} | |
// Increases the ship's velocity by it's acceleration value up to it's max speed. | |
public void Accelerate(int direction) | |
{ | |
// get our acceleration vector that we'll add to our velocity vector | |
Vector2 accel = new Vector2(Acceleration * direction, 0); | |
// adjust velocity now | |
Velocity += accel; | |
// make sure we aren't going over max speed in either direction. | |
// if so, set velocity to capped max speed in either direction | |
if (Velocity.Length() >= MaxSpeed || Velocity.Length() <= -MaxSpeed) | |
{ | |
Velocity.Normalize(); | |
Velocity = new Vector2(Velocity.X * MaxSpeed * direction, 0); | |
} | |
} | |
// Reduces the ship's velocity by it's acceleration value to a minimum of 0. | |
public void Decelerate() | |
{ | |
// if we're really close to stopping, just go ahead and stop | |
if (this.Velocity.Length() <= 0.1f || this.Velocity.Length() >= -0.1f) | |
{ | |
this.Velocity = Vector2.Zero; | |
return; | |
} | |
// get our acceleration vector in proper direction | |
Vector2 accel = Velocity; | |
accel.Normalize(); | |
accel *= -Acceleration; | |
// adjust velocity | |
Velocity += accel; | |
} | |
// adjust position based on velocity | |
public void Move() | |
{ | |
Position += Velocity; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment