Как мне переместить объект в квадратный узор? - PullRequest
0 голосов
/ 05 февраля 2019

У меня есть несколько ботов, которые могут двигаться, установив 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);


1 Ответ

0 голосов
/ 05 февраля 2019

Используя угол и кратчайшее расстояние до воображаемой квадратной дорожки, вы можете сделать треугольник.Одна вершина - игрок, одна - бот, а другая - то, где кратчайшее расстояние от игрока до дорожки пересекает дорожку.

Этот фрагмент является своего рода подтверждением концепции для вас.возможно, я смогу просто использовать вычисления положения и вставить их в свой код с вашими переменными, я просто использовал более длинные имена, чтобы попытаться облегчить чтение.

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...