Ship Flying Through Space

v1 Ship follows mouse around canvas. Boundary of universe is slightly smaller than canvas so we can see that the ship is prevented from leaving the universe.

by djwelsh

HTML

<canvas id="c" width="400" height="400"></canvas>
<div id="debug"></div>

CSS

#c {
    outline: 1px solid #ccc;
    width: 400px;
    height: 400px;
    margin: 10px;
}
#debug {
    position: fixed;
    right: 0px;
    top: 0px;
    width: 120px;
}

JavaScript

/* Trying to make a Google Maps-style app.
 * Attempting to allow the following:
 *  -panning (works)
 *  -zooming (works)
 * The problem:
 *  -centering the map on mouse coordinates after zooming
 */

//fix vector so ship approaches green ball
//keep green ball as a separate object maybe?
//draw vector from ship describing its orientation and speed (length of the line, obviously)


var canvas, ctx, colorOffset;
var c_width, c_height;
var ship = null;

//Size of universe in notional units. For now, 1nu = 1px (no zoom).
var universe = {
    leftWall : 0,
    rightWall : 300,
    topWall : 0,
    bottomWall : 300
};

var mouse = {
    x : 0, y : 0
};

function Vector (obj) {
    this.x = obj.x;
    this.y = obj.y;
}
Vector.prototype.magnitude = function () {
    return Math.sqrt(this.x * this.x + this.y * this.y);
};
Vector.prototype.normalize = function () {
    var mag = this.magnitude();
    if (mag === 0) mag = 0.0000001;
    var normalizedX = this.x / mag;
    var normalizedY = this.y / mag;
    
    return new Vector({ x : normalizedX, y : normalizedY });
};

function Ship(obj) {
    this.x = obj.x;
    this.y = obj.y;
    this.vx = 0;
    this.vy = 0;
    this.size = obj.size;
    
    this.speed = 0;
    
    this.strokeStyle = "#333";
    this.fillStyle = "#ccc";
    
}
//Calculate where we were, what our velocity is, and where we thus should be next. Calls draw() function after calculation.
Ship.prototype.updatePosition = function (context) {
    
    //New vx/vy is a vector based on mouse position relative to ship
    var V_DirectionOfShip = new Vector({
        x : mouse.x - ship.x,
        y : mouse.y - ship.y
    });
    var N_DirectionOfShip = V_DirectionOfShip.normalize();
    
    //Calculate speed based on distance of mouse from ship
    var M_DirectionOfShip = V_DirectionOfShip.magnitude();
    
    //Actual crowfly distance from mouse to ship
    var M_DistanceFromShipToMouse = V_DirectionOfShip.magnitude();
    
    //Adjust speed
    if...