javascript 角色跟踪实践
在javascript游戏中实现角色跟踪,核心是通过实时计算跟踪者与目标角色的坐标差值,再根据差值更新跟踪者的位置,常见于敌人AI、跟随宠物等场景。以下是基于Canvas的极简实践方案:
1. 核心原理
跟踪的本质是“让跟踪者向目标坐标移动”,关键步骤为:
1. - 获取跟踪者(follower)和目标(target)的实时坐标(x, y);
2. - 计算两者的坐标差值(dx = target.x - follower.x,dy = target.y - follower.y);
3. - 对差值进行“归一化”(避免斜向移动速度比横向/纵向快),得到移动方向向量;
4. - 根据跟踪速度,更新跟踪者的x、y坐标。
2. 完整代码实践(Canvas + 原生JS)
html<canvas id="gameCanvas" width="800" height="600" style="border:1px solid #000;"></canvas>
<script>
// 1. 初始化画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');// 2. 定义角色类(目标 + 跟踪者)
class Role {constructor(x, y, color, speed) {this.x = x; // x坐标this.y = y; // y坐标this.color = color; // 颜色(区分角色)this.speed = speed; // 移动速度}// 绘制角色(圆形)draw() {ctx.beginPath();ctx.arc(this.x, this.y, 20, 0, Math.PI * 2); // 半径20的圆ctx.fillStyle = this.color;ctx.fill();ctx.closePath();}// 跟踪目标的核心方法follow(target) {// 计算坐标差值const dx = target.x - this.x;const dy = target.y - this.y;// 计算两点间距离(避免除以0)const distance = Math.sqrt(dx * dx + dy * dy);if (distance < 5) return; // 距离过近时停止跟踪(防止抖动)// 归一化方向向量(确保各方向速度一致)const dirX = dx / distance;const dirY = dy / distance;// 更新跟踪者位置(速度 × 方向)this.x += dirX * this.speed;this.y += dirY * this.speed;}
}// 3. 创建角色实例
const player = new Role(400, 300, '#ff6b6b', 0); // 玩家(目标,初始不移动)
const follower = new Role(100, 100, '#4ecdc4', 3); // 跟踪者(绿色,速度3)// 4. 监听鼠标移动,让玩家(目标)跟随鼠标
canvas.addEventListener('mousemove', (e) => {const rect = canvas.getBoundingClientRect();// 转换鼠标坐标为Canvas内部坐标player.x = e.clientX - rect.left;player.y = e.clientY - rect.top;
});// 5. 游戏循环(实时更新 + 重绘)
function gameLoop() {// 清空画布ctx.clearRect(0, 0, canvas.width, canvas.height);// 跟踪者执行跟踪逻辑follower.follow(player);// 绘制两个角色player.draw();follower.draw();// 循环调用(浏览器刷新率同步)requestAnimationFrame(gameLoop);
}// 启动游戏
gameLoop();
</script>
游戏源码,点击下载:
https://store.cocos.com/app/detail/8060https://store.cocos.com/app/detail/80603. 关键优化点(避免常见问题)
- 防止抖动:当跟踪者与目标距离过近(如 distance < 5 )时停止移动,避免因坐标微小差值导致角色来回晃动。
- 速度统一:必须通过“距离归一化”计算方向向量,否则跟踪者斜向移动时(dx和dy同时存在),实际速度会是 √2 × 设定速度 ,导致移动不均衡。
- 性能控制:使用 requestAnimationFrame 而非 setInterval ,确保动画与浏览器刷新率同步,避免卡顿。
4. 扩展场景
- 范围跟踪:添加 if (distance > 300) return ,让跟踪者只在目标超出300像素范围时才启动跟踪。
- 障碍避让:若需避免跟踪者穿墙,可在 follow 方法中添加“碰撞检测”(如射线检测、网格碰撞),检测到障碍时调整移动方向。