Phaser3设置两个物体碰撞后缓慢回到指定位置
时间: 2024-01-01 09:04:14 浏览: 29
在Phaser3中,你可以通过Tween动画来让两个物体在碰撞后缓慢回到指定位置。具体操作如下:
1. 首先,你需要为两个物体添加物理引擎和Tween动画:
```
//创建两个精灵对象
var sprite1 = this.physics.add.sprite(x1, y1, 'sprite1');
var sprite2 = this.physics.add.sprite(x2, y2, 'sprite2');
//创建Tween动画对象
var tween1 = this.tweens.add({
targets: sprite1,
x: x1,
y: y1,
duration: 1000,
ease: 'Linear',
paused: true
});
var tween2 = this.tweens.add({
targets: sprite2,
x: x2,
y: y2,
duration: 1000,
ease: 'Linear',
paused: true
});
```
这里,我们创建了两个Tween动画对象,分别对应两个物体的回到指定位置动画。注意,paused属性设置为true,表示动画不会自动播放。
2. 接着,你需要为两个物体添加碰撞检测:
```
this.physics.add.collider(sprite1, sprite2, function(){
//碰撞后缓慢回到指定位置
tween1.restart();
tween2.restart();
});
```
这里使用的是`this.physics.add.collider`方法添加碰撞检测,当两个物体碰撞时,会触发回调函数。在回调函数中,我们将两个Tween动画对象的paused属性设置为false,让它们开始播放动画。
这样,当两个物体碰撞时,它们就会缓慢回到指定位置了。