我想将世界坐标中的点列表转换为屏幕中的点(像素)。 基本上我想将一个世界中的一堆(worldX,worldY)坐标乘以屏幕矩阵。
问题是这个程序非常慢。
代码:
for (int i = 0; i < cnt; i++)
{
worldX = getWorldX(i);
worldY = getWorldY(i);
screenX = wtsMat.vx1 * worldX + wtsMat.vy1 * worldY + wtsMat.tx;
screenY = wtsMat.vx1 * worldX + wtsMat.vy2 * worldY + wtsMat.ty;
...
//Do something with screenX and screenY
}
我想知道是否有更好更快的方法来完成这项任务。
答案 0 :(得分:0)
wtsMat变量在循环期间不会改变,那么为什么不将它们定义为变量而不是属性呢?
您的代码应该是这样的:
var worldX, worldY, screenX, screenY;
var wtsMatVx1 = wtsMat.vx1;
var wtsMatVy1 = wtsMat.vy1;
var wtsMatTx = wtsMat.tx;
var wtsMatVx2 = wtsMat.vx2;
var wtsMatVy2 = wtsMat.vy2;
var wtsMatTy = wtsMat.ty;
var i = cnt;
for (i; i > 0; i--)
{
worldX = getWorldX(i);
worldY = getWorldY(i);
screenX = wtsMatVx1 * worldX + wtsMatVy1 * worldY + wtsMatTx;
screenY = wtsMatVx1 * worldX + wtsMatVy2 * worldY + wtsMatTy;
...
//Do something with screenX and screenY
}
PS:对于使用screenY
来计算wtsMat.vx1
,这不应该是wtsMat.vx2
吗?
答案 1 :(得分:0)
考虑到它的工作,我猜计算是正确的,它只是一个速度问题。
此外,由于你遗漏了部分代码,我认为如果你对sceenX和screenY什么都不做,它也会很慢,所以它在你发布的循环中都是如此。 看到这是一个非常简单的计算,你的cnt必须非常高,因为它很慢。
你可以采取一些措施来加快速度:
//store object vars locally for quicker access
var wtsMatVx1 = wtsMat.vx1;
var wtsMatVy1 = wtsMat.vy1;
var wtsMatVy2 = wtsMat.vy2;
var wtsMatTx = wtsMat.tx;
var wtsMatTy = wtsMat.ty;
while (cnt--)
{
//while-- is faster according to tests
var worldX = getWorldX(i); //dont use a global scope, which is used if you dont use var
var worldY = getWorldY(i); //dont use a global scope
var screenX = wtsMatVx1 * worldX + wtsMatVy1 * worldY + wtsMatTx;
var screenY = wtsMatVx1 * worldX + wtsMatVy2 * worldY + wtsMatTy;
...
//Do something with screenX and screenY
}