2013-08-16 138 views
1

所以在我的画布上我有一个大的椭圆,当用户点击画布时,应该在大椭圆的边缘上创建一个小椭圆, 。这些角度是关闭的,我对计算不是很有信心,再加上我认为这个坐标系在下降时增加的事实正在让它变得更糟。任何人都可以帮助我获得理想的结果吗?计算从一个点到另一个的角度

HTML

<html> 
<head> 
    <script src='processing-1.4.1.min.js'></script> 
    <script src='jquery-1.9.1.min.js'></script> 
</head> 

<body> 
    <canvas id="gamecanvas" data-processing-sources="canvas.pde"></canvas> 
</body> 

<script> 
var gamecanvas = document.getElementById("gamecanvas"); 
var projectiles = []; 

$("#gamecanvas").click(function(e) { 
    var x = e.clientX - gamecanvas.offsetLeft; 
    var y = e.clientY - gamecanvas.offsetTop; 
    var pindex = projectiles.length; 
    projectiles[pindex] = []; 
    projectiles[pindex]['angle'] = Math.atan2(y - 200, x - 300) * 180/Math.PI; 
    projectiles[pindex]['x'] = 300 + 10 * Math.cos(projectiles[pindex]['angle']); 
    projectiles[pindex]['y'] = 200 + 10 * Math.sin(projectiles[pindex]['angle']); 
}); 
</script> 
</html> 

Processing.js帆布素描(Reference

void draw() { 
    size(600,400); 
    background(255,255,255); 
    fill(#FF0000); 
    ellipse(300,200,15,15); 
    for(i = 0;i < projectiles.length;i++) { 
     ellipse(projectiles[i]['x'],projectiles[i]['y'],2,2); 
    } 
} 

回答

2

您可以混合弧度和度。与角涉及JavaScript的数学函数需要弧度值:

MDN

的ATAN2方法返回-pi和pi 之间的数值表示的角度theta(X,Y )点。这是逆时针角度的 ,以弧度测量的,在正的X轴和点(x,y)之间。

而对于Math.cosMath.sin和:

单元弧度的给定的数字。

所以你可以尝试用这个代替:

/// keep radians, don't convert to degrees 
projectiles[pindex]['angle'] = Math.atan2(y - 200, x - 300); // * 180/Math.PI; 

projectiles[pindex]['x'] = 300 + 10 * Math.cos(projectiles[pindex]['angle']); 
projectiles[pindex]['y'] = 200 + 10 * Math.sin(projectiles[pindex]['angle']); 

除非你想保留这情况下,你需要做的这个度:

projectiles[pindex]['angle'] = Math.atan2(y - 200, x - 300) * 180/Math.PI; 

/// convert degrees back to radians 
projectiles[pindex]['x'] = 
      300 + 10 * Math.cos(projectiles[pindex]['angle'] * Math.PI/180); 
projectiles[pindex]['y'] = 
      200 + 10 * Math.sin(projectiles[pindex]['angle'] * Math.PI/180); 
相关问题