2D向量的数学计算

2D向量的数学计算


这些代码摘抄自BLIZZARDINTERFACECODEVector2D.lua部分

-- 数学意义在于向量围成的面积  a × b = |a||b|sinθ
-- 几何上二维向量叉乘是没有意义的,这个实现返回的值是垂直于向量a与向量b平面的向量的模,在3D数学中,向量叉乘返回的应该是一个向量
-- https://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product
-- 这个实现并不"合理",It's a shorthand notation for a mathematical hack.
function Vector2D_Cross(leftX, leftY, rightX, rightY)
	return leftX * rightY - leftY * rightX;
end

-- a·b = |a||b|cosθ
function Vector2D_Dot(leftX, leftY, rightX, rightY)
	return leftX * rightX + leftY * rightY;
end

--向量模的平方
function Vector2D_GetLengthSquared(x, y)
	return Vector2D_Dot(x, y, x, y);
end

-- 向量的模,注意求平方根是一个消耗较大的操作,所以若是简单的比较两个向量的模的大小可用模的平方代替.
function Vector2D_GetLength(x, y)
	return sqrt(Vector2D_GetLengthSquared(x, y));
end

-- 单位向量
function Vector2D_Normalize(x, y)
	return Vector2D_DivideBy(Vector2D_GetLength(x, y), x, y);
end

-- 两个向量的夹角度:  tanθ = sinθ /cosθ;atan2(x,y) = atan(y/x)
function Vector2D_CalculateAngleBetween(leftX, leftY, rightX, rightY)
	return atan2(Vector2D_Cross(leftX, leftY, rightX, rightY), Vector2D_Dot(leftX, leftY, rightX, rightY));
end

-- 旋转弧度
function Vector2D_RotateDirection(rotationRadians, x, y)
	local cosValue = cos(rotationRadians);
	local sinValue = sin(rotationRadians);
	return x * cosValue - y * sinValue, x * sinValue + y * cosValue;
end
原文地址:https://www.cnblogs.com/Fallever/p/11195368.html