gpt4 book ai didi

javascript - 如何以方形图案移动对象?

转载 作者:行者123 更新时间:2023-12-01 01:18:10 24 4
gpt4 key购买 nike

我有一些机器人可以通过设置 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);


最佳答案

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

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

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>

关于javascript - 如何以方形图案移动对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54525658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com