这一篇主要包含了一些数学函数和颜色等,代码中有简单注释。
cc = cc or {}
function cc.clampf(value, min_inclusive, max_inclusive) --将value限制在min_inclusinve,max_inclusive之间
-- body
local temp = 0
if min_inclusive > max_inclusive then
temp = min_inclusive
min_inclusive = max_inclusive
max_inclusive = temp
end
if value < min_inclusive then
return min_inclusive
elseif value < max_inclusive then
return value
else
return max_inclusive
end
end
--Point 坐标向量
function cc.p(_x,_y)
if nil == _y then
return { x = _x.x, y = _x.y }
else
return { x = _x, y = _y }
end
end
function cc.pAdd(pt1,pt2) --两向量相加
return {x = pt1.x + pt2.x , y = pt1.y + pt2.y }
end
function cc.pSub(pt1,pt2) --两向量相减
return {x = pt1.x - pt2.x , y = pt1.y - pt2.y }
end
function cc.pMul(pt1,factor) --两向量相乘
return { x = pt1.x * factor , y = pt1.y * factor }
end
function cc.pMidpoint(pt1,pt2) --两向量的中点
return { x = (pt1.x + pt2.x) / 2.0 , y = ( pt1.y + pt2.y) / 2.0 }
end
function cc.pForAngle(a) --返回坐标x = cos(a),y = sin(a)
return { x = math.cos(a), y = math.sin(a) }
end
function cc.pGetLength(pt) --向量长度
return math.sqrt( pt.x * pt.x + pt.y * pt.y )
end
function cc.pNormalize(pt) --标准向量化
local length = cc.pGetLength(pt)
if 0 == length then
return { x = 1.0,y = 0.0 }
end
return { x = pt.x / length, y = pt.y / length }
end
function cc.pCross(self,other) --点积
return self.x * other.y - self.y * other.x
end
function cc.pDot(self,other) --叉积
return self.x * other.x + self.y * other.y
end
function cc.pToAngleSelf(self) --将斜率转为角度
return math.atan2(self.y, self.x)
end
function cc.pGetAngle(self,other) --向量夹角弧度
local a2 = cc.pNormalize(self)
local b2 = cc.pNormalize(other)
local angle = math.atan2(cc.pCross(a2, b2), cc.pDot(a2, b2) )
if math.abs(angle) < 1.192092896e-7 then
return 0.0
end
return angle
end
function cc.pGetDistance(startP,endP) --坐标距离
return cc.pGetLength(cc.pSub(startP,endP))
end
function cc.pIsLineIntersect(A, B, C, D, s, t) --判断直线AB和直线CD是否相交
if ((A.x == B.x) and (A.y == B.y)) or ((C.x == D.x) and (C.y == D.y))then
return false, s, t
end
local BAx = B.x - A.x
local BAy = B.y - A.y
local DCx = D.x - C.x
local DCy = D.y - C.y
local ACx = A.x - C.x
local ACy = A.y - C.y
local denom = DCy * BAx - DCx * BAy
s = DCx * ACy - DCy * ACx
t = BAx * ACy - BAy * ACx
if (denom == 0) then
if (s == 0 or t == 0) then
return true, s , t
end
return false, s, t
end
s = s / denom
t = t / denom
return true,s,t
end
function cc.pPerp(pt) --逆时针旋转90度
return { x = -pt.y, y = pt.x }
end
function cc.RPerp(pt) --顺时针旋转90度
return { x = pt.y, y = -pt.x }
end
function cc.pProject(pt1, pt2) --pt1在pt2上投影,最后投影到x轴
return { x = pt2.x *