So I'm sure the answer to this will be something simple and I'll read it and immediately commence epic facepalming, but at the moment I've spent an entire day wondering why the heck this isn't working and I just can't find the problem...
I'm trying to build a simple (supposed to be anyway) system to rotate 2d points around a central axis, but I've found 2 problems so far that make no sense to me whatsoever.
Problem 1: The positive/negative numbers assigned to the input object are being flipflopped in a seemingly random fashion. Problem 2: The rotation math is correct, but the results are anything but.
Here's the code to reproduce this开发者_开发知识库 problem:
function doRotate(pos){
//convert angle to radians
var ang = 90 * Math.PI / 180;
//rotate points
pos.left = Math.round(pos.left * Math.cos(ang) + pos.top * Math.sin(ang));
pos.top = Math.round(pos.top * Math.cos(ang) - pos.left * Math.sin(ang));
return pos;
}
var points = {
'a':{left:32,top:32},
'b':{left:-32,top:32},
'c':{left:-32,top:-32},
'd':{left:32,top:-32}
};
for( var k in points ){
var msg = 'Start: X:'+points[k].left+' Y:'+points[k].top+'<br />';
points[k] = doRotate(points[k]);
var msg = msg+'End: X:'+points[k].left+' Y:'+points[k].top+'<br />';
document.write( '<p>'+k+':<br />'+msg+'</p>' );
}
Now you'd expect to see: a: Start: X:32 Y:32 End: X:32 Y:-32
b: Start: X:-32 Y:32 End: X:-32 Y:-32
c: Start: X:-32 Y:-32 End: X:-32 Y:32
d: Start: X:-32 Y:32 End: X:32 Y:32
But instead you get this:
a: Start: X:32 Y:32 End: X:32 Y:32
b: Start: X:-32 Y:-32 End: X:32 Y:32
c: Start: X:-32 Y:-32 End: X:-32 Y:-32
d: Start: X:32 Y:32 End: X:-32 Y:-32
I've triple checked the math and that is 100% accurate to rotate points around origin in 2D. I've even recreated this test in PHP and it works perfectly. What I can't figure out is why the heck JS is a) screwing up the variable assignments and b) not coming up with the correct results?
Anyone who can help may rest assured that I will salute their insight with a facepalm Sir Patrick would be proud of ;)
Wait a sec - shouldn't you save pos.left
before you compute pos.top
so that you can use the old pos.left
value in that calculation?
In your "var msg = ..." statements, you're printing points[k].left twice, and never printing points[k].top.
Commence facepalm:
for( var k in points ){
var msg = 'Start: X:'+points[k].left+' Y:'+points[k].left+'<br />';
points[k] = doRotate(points[k]);
var msg = msg+'End: X:'+points[k].left+' Y:'+points[k].left+'<br />';
document.write( '<p>'+k+':<br />'+msg+'</p>' );
}
should read
for( var k in points ){
var msg = 'Start: X:'+points[k].left+' Y:'+points[k].top+'<br />';
points[k] = doRotate(points[k]);
var msg = msg+'End: X:'+points[k].left+' Y:'+points[k].top+'<br />';
document.write( '<p>'+k+':<br />'+msg+'</p>' );
}
You're printing the left
property for Y when you should be printing the top
property
精彩评论