javascript - Calculating the angle from one point to another -
so on canvas have large ellipse, , when user clicks on canvas small ellipse should created on edge of large ellipse in direction of click was. angles off, , i'm not confident in calculations, plus think fact coordinate system has y increasing when goes down screwing up. can me desired result?
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); } }
you mix radians , degrees here. javascript math functions deals angles needs radian values:
from mdn:
the atan2 method returns numeric value between -pi , pi representing angle theta of (x,y) point. counterclockwise angle, measured in radians, between positive x axis, , point (x,y).
a number given in unit of radians.
so try instead:
/// keep radians, don't convert 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']);
unless want keep degrees in case need this:
projectiles[pindex]['angle'] = math.atan2(y - 200, x - 300) * 180 / math.pi; /// convert degrees 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);
Comments
Post a Comment