首页 > 解决方案 > 如何以方形模式移动对象?

问题描述

我有一些机器人可以通过设置 x 和 y 来移动。我已经能够让它们以圆形模式移动,但是如何让它们以方形模式旋转?我数学不是很好,所以我很感激一些帮助。

这是我做圆形图案的方法。

var PI2 = 2 * Math.PI, FOLLOWADD = PI2 / 18/*PI2 / 360 * 20*/, BOTSLICE = PI2 / BOTS;

bots.follow = function(id) {
    if (!ppl()[id])
        id = protocol.id; //player is default

    var pos = getPos(id), a, i = BOTS;
    while (i--)
        if (this[i] && !this.busy) {
            a = BOTSLICE * i + f;
          this[i].pos.x = pos.x + (Math.cos(2 * Math.PI / BOTS * i + f) * 3);
            this[i].pos.y = pos.y + (Math.sin(2 * Math.PI / BOTS * i + f) * 3);
        }
    f = (f + FOLLOWADD) % PI2;
}.bind(bots);


标签: javascriptmath

解决方案


使用角度和到假想的方形轨道的最短距离,您可以制作一个三角形。一个顶点是玩家,一个是机器人,另一个是玩家到赛道的最短距离与赛道相交的地方。

这个片段对您来说是一种概念证明,您可能可以只使用位置计算并将它们与您的变量一起放入您的代码中,我只是使用更长的名称来尝试使其更易于阅读。

const player = $( '#player' );
const bot = $( '.bot' );

const radius = 50; // this is the shortest distance from the center to the edge
const numSteps = 180;
const eigthOfCircle = ( Math.PI * 2 ) / 8;
const angleStepSize = Math.PI * 2 / numSteps; // split the circle into steps.

let angle = 0;

setInterval( function() {
  let xPlayer = player.offset().left;
  let yPlayer = player.offset().top;
  
  let x = 0, y = 0;
  
  if ( angle < eigthOfCircle || angle > eigthOfCircle * 7 ) {
    y = - radius + 15;
    x = Math.sin( angle ) * radius;
  }
  else if ( angle < eigthOfCircle * 3 ) {
    x = radius - 15;
    y = - Math.cos( angle ) * radius;
  }
  else if ( angle < eigthOfCircle * 5 ) {
    y = radius - 15;
    x = Math.sin( angle ) * radius;
  }
  else if ( angle < eigthOfCircle * 7) {
    x = - radius + 15;
    y = - Math.cos( angle ) * radius;
  }
  
  bot.css( { 
    left: xPlayer + x + 'px', 
    top: yPlayer + y + 'px',
  });
  
  angle += angleStepSize;
  angle = angle > Math.PI * 2 ? 0 : angle;
  
  console.log( xPlayer, yPlayer, angle, Math.sin( angle ), Math.cos( angle ) );
}, 20 );
#player {
  width: 20px;
  height: 20px;
  background-color: red;
  position: absolute;
  top:30%;
  left:50%;
  transform: translate( -50%, -50% );
}

.bot {
  width: 20px;
  height: 20px;
  background-color: green;
  position: absolute;
  top:0;
  left:0;5
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="player"></div>
<div class="bot"></div>


推荐阅读