所以在我的画布上我有一个大的椭圆,当用户点击画布时,应该在大椭圆的边缘沿着点击的方向创建一个小椭圆。角度是关闭的,我对计算不是很有信心,而且我认为这个坐标系在下降时会增加的事实是搞砸了。任何人都可以帮助我获得理想的结果吗?
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 Canvas Sketch(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);
}
}
答案 0 :(得分:1)
你在这里混合弧度和度数。处理角度的JavaScript Math函数需要 radian 值:
来自MDN:
atan2方法返回-pi和pi之间的数值 表示(x,y)点的角度θ。这是 逆向角,以弧度测量,在正X之间 轴和点(x,y)。
以弧度单位给出的数字。
所以你可以试试这个:
/// 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);