EVA.js学习笔记(二)入门
EVA.js学习笔记(四)实践fappy-bird游戏(上)
基于目前使用VUE的框架做项目,我会以vue的方式来进行学习。
基本流程
安装,创建画布,添加资源,创建游戏,添加游戏对象
eva.js是按需引入,所以使用不同的组件,需要安装不同的包。
1、安装
在官方有2种安装方式,一种是通过NPM,一种是通过
使用NPM
\
npminstall @eva/eva.js
2、创建画布
Eva.js 依赖于 HTML 中的 canvas 进行绘制。如果设计稿中的宽高是固定的(例如 750px*1000px)又占满全屏,我们可以设置 canvas 的 css 宽度为 100%,高度为 auto。
在我们的inde.vue文件中创建一个canvas,id为canvas
<template>
<div>
<canvas id="canvas"></canvas>
</div>
</template>
<style>
#canvas {
width: 100%;
height: auto;
}
</style>
3、添加资源
在创建游戏之前,我们需要添加资源文件到资源管理器中,一般是使用一个文件将这些资源都全部放在一起。
在项目中新建一个resource.js文件,在我们的vue代码中引入加载资源
静态文件需要放在 项目目录/public/路径下面,否则会无法读取(就算VSCODE里面能显示出图片,在eva.js里也无法读取)
以上图片我在vscode里已经可以找到了,但是在eva.js的资源文件里读取不到。
在这里我的resource.js是放在 项目路径/src/views 中 ,从以下的 url: "../bg.png"上看并不是正确的路径。但是能访问到。这里弄了好久。
import { RESOURCE_TYPE } from "@eva/eva.js";
export default [
{
name: "bg",
type: RESOURCE_TYPE.IMAGE,
src: {
image: {
type: "png",
url: "../bg.png",
},
},
preload: true,
},
];
4、创建游戏
Eva.js 内核是一个非常轻量级的运行时,其他功能都是通过插件的方式实现的,如果想实现游戏最基础的渲染能力,需要安装渲染插件 @eva/plugin-renderer。
npm i @eva/plugin-renderer
加载游戏需要在mouted中加载,如果在created中加载则会在渲染完成之前创建,就不会渲染出来。
resource用来是加载之前创建在source.js的资源
<template>
<div>
<canvas id="canvas"></canvas>
</div>
</template>
<script>
import { resource, Game, GameObject, RESOURCE_TYPE } from "@eva/eva.js";
import { RendererSystem } from '@eva/plugin-renderer'
import resource from "./sources";
export default {
created() {},
mounted() {
this.show();
},
methods: {
show() {
//加载资源
resource.addResource(sources);
// 创建渲染系统
const rendererSystem = new RendererSystem({
canvas: document.querySelector('#canvas'), // 可选,自动生成 canvas 挂在 game.canvas 上
width: 750,
height: 1000,
transparent: false,
resolution: window.devicePixelRatio / 2, // 可选, 如果是2倍图设计 可以除以2
enableScroll: true, // 允许页面滚动
renderType: 0 // 0:自动判断,1: WebGL,2:Canvas,建议android6.1 ios9 以下使用Canvas,需业务判断。
})
// 创建游戏对象
const game = new Game({
frameRate: 60, // 可选,游戏帧率,默认60
autoStart: true, // 可选,自动开始
systems: [rendererSystem]
})
}
}
</script>
<style>
#canvas {
width: 100%;
height: auto;
}
</style>
当然这样只让 Eva.js 有了基础的渲染能力,但是 canvas 上还没有展示任何元素,接下来我们将添加 gameObject,它将会展现在画布上。
5、添加游戏对象
添加一个text对象,输出一个Hello word!,首先需要安装Text组件(在eva.js中,每一个文本,图片都是一个组件,都需要安装对于的包)
npm i @eva/plugin-renderer @eva/plugin-renderer-text
引入
import { Text, TextSystem } from '@eva/plugin-renderer-text'
需要在之前创建的game中,创建TextSystem()
...
// 创建游戏对象
const game = new Game({
frameRate: 60, // 可选,游戏帧率,默认60
autoStart: true, // 可选,自动开始
systems: [
rendererSystem,
new TextSystem()
]
})
...
//创建GameObject
const text = new GameObject("text", {
position: {
x: 0,
y: 0
},
});
//创建一个文字组件
const textCompont = new Text({
text: "hello word!",
style: {
fontFamily: "Arial",
fontSize: 36,
fontStyle: "italic",
fontWeight: "bold",
fill: "#fff",//文字填充颜色
}
})
//将组件添加到text这个对象里
text.addComponent(textCompont);
//显示到画布上面
game.scene.addChild(text)
npm run serve 后,我们的hello word就写好了。
做完这个例子再来复习下这个图,就能有更好的理解。
.
更多的组件和内容可以在官方的eva.js.org/playground/…/学习。
若有收获,就点个赞吧