有意思的逻辑问题:关于AB运动轨迹问题

A始终朝向B,B始终跟A垂直,如果两者速度相等,运动轨迹
在这里插入图片描述
代码:

<!DOCTYPE html>
<html>
<head>
    <title>Point Movement</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500"></canvas>

    <script>
        const canvas = document.getElementById("myCanvas");
        const context = canvas.getContext("2d");

        const A = {x: 100, y: 100}; // 红点的起始位置
        const B = {x: 400, y: 400}; // 蓝点的起始位置
        const v = 2; // 点的速度

        function drawPoint(point, color) {
            context.beginPath();
            context.arc(point.x, point.y, 5, 0, Math.PI * 2, true);
            context.closePath();
            context.fillStyle = color;
            context.fill();
        }

        function drawLine(point1, point2, color) {
            context.beginPath();
            context.moveTo(point1.x, point1.y);
            context.lineTo(point2.x, point2.y);
            context.strokeStyle = color;
            context.stroke();
        }

        function update() {
            // 计算红点应该移动的方向
            const angle = Math.atan2(B.y - A.y, B.x - A.x);

            // 计算红点的新位置
            A.x += v * Math.cos(angle);
            A.y += v * Math.sin(angle);

            // 计算蓝点的新位置
            B.x += v * Math.cos(angle - Math.PI / 2);
            B.y += v * Math.sin(angle - Math.PI / 2);

            // 绘制红点和蓝点
            drawPoint(A, "red");
            drawPoint(B, "blue");

            // 绘制红点和蓝点之间的连线
            drawLine(A, B, "black");

            // 延迟一段时间后更新下一帧
            setTimeout(update, 10);
        }

        update(); // 开始运行
    </script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值