本来效果挺流畅,截屏成gif图有点卡。
素材
wave.png 1280*140
思路
2个图片,叠加一起,运动方向互为相反。
gameObjects
在evajs游戏引擎中,万物皆gameObjects。所以两个海浪的图片,要先建2个实体,也就是gameObjects
- WaveBack
const WaveBack = () => {
const go = new GameObject("WaveFront", {
size: {
width: 1280,
height: 140
},
origin: { x: 0, y: 0 },
position: {
x: GAME_SIZE.WIDTH - 1280 * 2,
y: GAME_SIZE.HEIGHT - 140
},
scale: {
x: 2,
y: 1
},
anchor: {
x: 0,
y: 0
}
});
go.addComponent(
new Img({
resource: "wave",
})
);
go.addComponent(
new Render({
alpha: 0.5
})
)
go.addComponent(new WaveAction(Direction.right))
return go;
}
export default WaveBack
- WaveFront
const WaveFront = () => {
const go = new GameObject("WaveFront", {
size: {
width: 1280,
height: 140
},
origin: { x: 0, y: 0 },
position: {
x: 0,
y: GAME_SIZE.HEIGHT - 100
},
scale: {
x: 2,
y: 1
},
anchor: {
x: 0,
y: 0
}
});
go.addComponent(
new Img({
resource: "wave",
})
);
go.addComponent(
new Render({
alpha: 0.3
})
)
go.addComponent(new WaveAction(Direction.left))
return go;
}
export default WaveFront
透明度
让海浪具有透明度,可以在每个gameObject增加Render组件以设置透明度。
addComponent(
new Render({
alpha: 0.3
})
)
行为控制
新建一个WaveAction组件,extends自Component。
它的作用就是让波浪动起来。
export enum Direction {
left,
right
}
export class WaveAction extends Component {
gameObject: GameObject;
static componentName = "Wave";
game: any
direction: Direction
constructor(direction: Direction) {
super();
this.direction = direction
}
update() {
const { x } = this.gameObject.getComponent(Transform).position
if (this.direction == Direction.left) {
this.gameObject.getComponent(Transform).position.x -= 6
}
if (this.direction == Direction.right) {
this.gameObject.getComponent(Transform).position.x += 6
}
if (x >= 0 && this.direction == Direction.right) {
this.direction = Direction.left
}
if (x <= -1280 * 2 + GAME_SIZE.WIDTH && this.direction == Direction.left) {
this.direction = Direction.right
}
}
}
关键点在于方向的判断
const { x } = this.gameObject.getComponent(Transform).position
if (this.direction == Direction.left) {
this.gameObject.getComponent(Transform).position.x -= 6
}
if (this.direction == Direction.right) {
this.gameObject.getComponent(Transform).position.x += 6
}
if (x >= 0 && this.direction == Direction.right) {
this.direction = Direction.left
}
if (x <= -1280 * 2 + GAME_SIZE.WIDTH && this.direction == Direction.left) {
this.direction = Direction.right
}
最后,把gameObjects加入到场景中:
const scene = new Scene('game');
game.loadScene({
scene,
type: LOAD_SCENE_MODE.SINGLE,
} as any);
scene.addChild(BackGround());
scene.addChild(WaveFront());
scene.addChild(WaveBack());
game.start();
由于帖全部代码会影响阅读,因此本文只贴了关键代码,全部代码在 github.com/codetyphon/…