一, 笛卡尔坐标系
笛卡尔坐标系是数学中的坐标系,而计算机中则采用屏幕坐标系统.
而三维坐标系则没有一个工业标准,分别有 Y轴向上(y-up)的坐标系, Z轴向上(z-up)的坐标系, 右手坐标系(right-handed coordinate system), 左手坐标系(left-handed coordinate system).
下面的是y-up left-handed coordinate system
数学中通常以括号加住的方式,如P(x,y,z)来表示点, 而程序中通常使用p<x,y,z>或p[x,y,z]表示点.代码片段:
function Point2D(x, y){
this.x = x
this.y = y
}
function Point3D(x, y, z){
this.x = x
this.y = y
this.z = z
}
二, 线
1. 求两点之间的距离
勾股定理: a2 + b2 = c2
2D场景中, 假设要获取P1(x1, y1)与P2(x2, y2)之间的距离d, 计算公式:
/*
*@param {Point2D} p1
*@param {Point2D} p2
*@return {number}
*/
function distance2D(p1, p2){
var dX = p1.x - p2.x
, dY = p1.y - p2.y
return Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2))
}
3D场景中,假设要获取P1(x1, y1, z1)与P2(x2, y2, z2)之间的距离d, 计算公式:
/*
*@param {Point3D} p1
*@param {Point3D} p2
*@return {number}
*/
function distance3D(p1, p2){
var dX = p1.x - p2.x
, dY = p1.y - p2.y
, dZ = p1.z - p2.z
return Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2) + Math.pow(dZ, 2))
}
2. 斜率
数学公式:
, slope为正数则直线横穿第一和第三像限, 为负数则直线横穿第二和第四像限.
直线公式: y = slope * x + b
, b为直线与Y轴交点离原点的偏移量.
假设直线A为y1 = slope1 * x1 + b1, 而直线B为y2 = slope2 * x2 + b2
if (slope1 === slope2){
console.log("A与B平行")
if (b1 === b2)
console.log("A与B重合")
}
else{
console.log("A与B相交")
if (-1 === slope1 * slope2)
console.log("A与B相互垂直")
}
三, 抛物线
抛物线分为4个方向
假设抛物线定点P(x1,y1)
Y轴对称的抛物线: y = a(x - x1)2 + y1 , a为正数则开口向上, a为负数则开口向下.
X轴对称的抛物线: x = a(y - y1)2 + x1, a为正数则开口向右, a为负数则开口向左.
四, 圆
假设圆心坐标P(x1, y1), 半径为r.
公式: (x - x1)2 + (y - y1)2 = r2
/*
* @constructor
* @param {Point2D} point 圆心坐标
* @param {number} r 半径
*/
function Circle(point, r){
this.point = point
this.r = r
}
碰撞算法基础: 两圆相切或相交
公式:
/*
*@param {Circle} c1
*@param {Circle} c2
*@return {boolean}
*/
function isHit(c1, c2){
var dCenter = Math.sqrt(Math.pow(c1.center.x - c2.center.x, 2) + Math.pow(c1.center.y - c2.center.y, 2))
var totalRadius = c1.r + c2.r
return dCenter <= totalRadius
}
五, 球(3D)
假设球心坐标P(x1,y1,z1), 半径为r
公式: (x - x1)2 + (y - y1)2 + (z - z1)2 = r2
/*
*@param {Point3D} center
*@param {number} r
*/
function Sphere(center, r){
this.center = center
this.radius = r
}
碰撞算法基础: 两球相切或相交
/*
*@param {Sphere} c1
*@param {Sphere} c2
*@return {boolean}
*/
function isHit(c1, c2){
var dCenter = Math.sqrt(Math.pow(c1.center.x - c2.center.x, 2) + Math.pow(c1.center.y - c2.center.y, 2) + Math.pow(c1.center.z - c2.center.z, 2))
var totalRadius = c1.r + c2.r
return dCenter <= totalRadius
}
六, 弧度和角度
以笛卡尔坐标系的P(0,0)作为角点. 初始边为X轴的正半轴, 终边与初始边构成一个夹角.
初始边逆时针旋转得到的夹角度数为正值, 顺时针旋转得到的夹角度数为负值.
π≈3.141592654
角度:degree=radian*180/π
弧度:radian=degree*π/180
function getDegree(radian){
return radian * 180 / Math.PI
}
function getRadian(degree){
return degree * Math.PI / 180
}
参考: http://www.cnblogs.com/HelloCG/