Ship Flying Through Space

v3 Scaling of the minimap and cropping of unnecessary data v2 Minimap using the same data as the larger map. 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>
<canvas id="_c" width="400" height="400"></canvas>
<div id="debug"></div>

CSS

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

JavaScript

var canvas, ctx, _canvas, _ctx, colorOffset;
var c_width, c_height;
var ship = null;
var dummies = [];

//The amount by which the main map should be multiplied to get the minimap the size we want
var scaleOfMiniMap = 0.25;
var cropMiniMap = true;
//The position of the minimap on the screen
var positionOfMiniMap = {
    x : 30,
    y : 310
};
//The square or circle that defines how much of the minimap to show. 
var sizeOfMiniMap = {
    width : 80,
    height : 40
};

//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, offsets) {
    
    //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();
    
   ...