Phaser中如何让精灵组子对象随运动方向旋转(碰撞时更新)
实现Phaser精灵朝向运动方向并碰撞后更新朝向
问题背景
已创建Phaser精灵组及相机控制,相关代码如下:
精灵组创建代码:
this.photons = this.physics.add.group({ key: "photon", repeat: 11, setXY: { x: 50, y: 50, stepX: 32 }, }); this.photons.children.iterate(function (child) { child.body.bounce.set(1); child.setVelocity(Phaser.Math.Between(300, 500),20); child.body.collideWorldBounds = true; });
碰撞设置:
this.physics.add.collider(this.photons, this.photons);
相机控制代码:
const cursors = this.input.keyboard.createCursorKeys(); const controlConfig = { camera: this.cameras.main, left: cursors.left, right: cursors.right, up: cursors.up, down: cursors.down, acceleration: 0.06, drag: 0.0005, maxSpeed: 1.0, }; this.controls = new Phaser.Cameras.Controls.SmoothedKeyControl( controlConfig );
需求:让每个精灵朝向自身运动向量方向,且碰撞后自动更新朝向。
解决方案
核心逻辑是通过精灵的速度向量计算旋转角度,在每帧更新时同步应用该角度,确保碰撞后速度变化时朝向实时更新。
1. 初始设置旋转角度
在创建精灵时,根据初始速度计算并设置初始朝向:
this.photons.children.iterate(function (child) { child.body.bounce.set(1); child.setVelocity(Phaser.Math.Between(300, 500),20); child.body.collideWorldBounds = true; // 根据初始速度计算旋转角度 child.setRotation(Phaser.Math.Angle.Between(0, 0, child.body.velocity.x, child.body.velocity.y)); });
2. 在update循环中持续更新朝向
在场景的update方法中,遍历精灵组,每帧根据当前速度更新旋转角度:
update(time, delta) { // 相机控制更新 this.controls.update(delta); // 更新每个光子的朝向 this.photons.children.iterate(function (child) { // 根据当前速度向量计算角度 const angle = Phaser.Math.Angle.Between(0, 0, child.body.velocity.x, child.body.velocity.y); child.setRotation(angle); }); }
补充:碰撞时强制更新(可选)
如果需要在碰撞瞬间立即同步朝向(避免帧延迟),可以给碰撞器添加回调函数:
this.physics.add.collider(this.photons, this.photons, function(photon1, photon2) { // 更新两个碰撞光子的朝向 photon1.setRotation(Phaser.Math.Angle.Between(0,0, photon1.body.velocity.x, photon1.body.velocity.y)); photon2.setRotation(Phaser.Math.Angle.Between(0,0, photon2.body.velocity.x, photon2.body.velocity.y)); });
原理说明
Phaser.Math.Angle.Between(0,0, vx, vy):计算从原点(0,0)到速度向量(vx, vy)的角度,该角度即为精灵需要朝向的方向。- 每帧更新旋转能确保任何速度变化(包括碰撞反弹、边界反弹)后,朝向立即同步。
内容的提问来源于stack exchange,提问作者Vatsa Pandey
相关产品推荐
相关产品推荐

