我有一些机器人可以通过设置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);
答案 0 :(得分:2)
使用角度和与假想方形轨迹的最短距离,您可以制作一个三角形。一个顶点是玩家,一个顶点是机器人,另一个顶点是玩家到轨道的最短距离与轨道相交的地方。
此代码段对您来说是一种概念证明,您也许可以只使用位置计算并将其与变量一起放入代码中,我只是使用了更长的名称来尝试使其更易于阅读
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>