我有一个跟随鼠标的点,我怎么能给它一个有限的转弯率?

时间:2018-01-06 20:19:51

标签: java methods processing trigonometry

我有一点跟随我在Processing中制作的鼠标。

<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
   </head>
   <body>
      <div ng-app="myApp" align="center" ng-controller="myCtrl">
         <a href="javascript:;" ng-init="watchlistexpand = null;changeDataPlacement='left'" ng-click="watchlistexpand = !watchlistexpand; changePlacement();" title="{{ watchlistexpand ? 'Compact' : 'Expand'}} View">{{ watchlistexpand ? 'Compact' : 'Expand'}} View</a>
         <div ng-repeat = "item in items">
            <a href="#" data-toggle="tooltip" data-placement="{{(changeDataPlacement === 'left')? 'left':'right'}}" title="Hooray!">{{item}}</a>
         </div>
      </div>
   </body>
</html>

我怎么能改变这个或添加到这个以使得该点具有有限的转弯率?我的想法与这场比赛中的导弹相似。 https://scratch.mit.edu/projects/181364872/ 我不知道我是怎么开始限制转折点的。任何帮助将不胜感激。

(我也标记了java,因为虽然这是在Processing中,但很多时候,Processing几乎都是带有内置方法的Java。)

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是保持对象的当前方向。然后,您可以使用向量与鼠标的交叉积,以及沿对象方向的向量,以找到需要转向指向鼠标的角度。然后,您可以限制转弯并添加更改以获得新方向。

double direction = ?; // the current direction of object in radians
double x = ?;  // the current position
double y = ?;
double maxTurn = ?; // Max turn speed in radians
double speed = ?;
void move() {
   double mvx = mouseX - x;   // get vector to mouse
   double mvy = mouseY - y;
   double dist = Math.sqrt(mvx * mvx + mvy * mvy);  // get length of vector
   if(dist > 0){  // must be a distance from mouse
       mvx /= dist;  // normalize vector
       mvy /= dist; 
       double ovx = Math.cos(direction); // get direction vector
       double ovx = Math.sin(direction);
       double angle = Math.asin(mvx * ovy - mvy * ovx); // get angle between vectors
       if(-mvy * ovy - mvx * ovx < 0){ // is moving away
          angle = Math.sign(angle) * Math.PI - angle;  // correct angle
       }
       // angle in radians is now in the range -PI to PI
       // limit turn angle to maxTurn
       if(angle < 0){
          if(angle < -maxTurn){
             angle = -maxTurn;
          }
       }else{
          if(angle > maxTurn){
             angle = maxTurn;
          }
       }
       direction += angle; // turn 
       // move along new direction
       x += Math.cos(direction) * speed;
       y += Math.sin(direction) * speed;
    }
}