使用鸿蒙开发手表游戏?小恐龙跳?仙人掌

demo

screen.gif

上面是在DevEco Studio 2.1模拟器中的效果。因为我没有购买鸿蒙手表,所以还没有在真机上运行。欢迎有手表的朋友生成hpp在真机运行。

安装 DevEco Studio 2.1

首先,先安装DevEco Studio 2.1,没有的可以去鸿蒙开发者官网 developer.harmonyos.com/cn/develop/… 下载。

新建一个lite Empty Ability(js)项目。

lite

Project Type 选择 Application,api 选择 api version 5,Device Type 选择 lite Wearable 就可以了。

next

项目结构

dir

可以看到,项目结构有点像小程序。

canvas组件哪儿去了?

因为我们要在这上面开发游戏,所以首先想到的是canvas。

然而。。。

no canvas

编辑器竟然提示没有canvas组件。

后来我还专门去开发者论坛问了一下,但是对方说,canvas是有的。

经过我的研究,发现canvas在手机app里是可以的,但是在手表里是没有的。而我们新建的是手表项目,所以canvas不可用。

这里需要注意的是,此鸿蒙非彼鸿蒙。手表里的鸿蒙和手机上的鸿蒙不是一回事儿。所以以前开发android的经验,在这里就翻车了。

用图片替代

既然没有canvas,还好有image组件。

但是image组件也有问题,就是它不能缩放。而且必须在css里定义大小,否则图片就不显示。

所以以前使用双倍大小的图片,在这里不行。

dino.png

因此,必须把图片裁剪好,然后在代码里指定大小:

.dino{
    width: 90px;
    height: 96px;
}
复制代码

定位不能用position,因为它不支持

需要使用stack组件作为父组件,然后把image组件放在stack组件里作为子组件。

<stack class="container" onclick="click">
    <image id="dino" style="left: {{dino.x}}; top: {{dino.y}};" class="dino" src="https://juejin.cn/common/{{ dino.frame }}.png"></image>
</stack>
复制代码

为了定位,需要在image标签里设置style,属性为left和top。相应的,在index.js里:

dino: {
    w:90,
    h:96,
    x:80,
    y:300,
    frame:'dino',
},
复制代码

这样就完成了dino小恐龙的定位。

小恐龙的跑步状态

a.png

b.png

准备了两张图,在游戏的循环中,让time自增1:

time+=1
复制代码

然后根据时间差,让他俩交替替换。

if(time%2==0){
    dino.frame='a'
}
if(time%4==0){
    dino.frame='b'
}
复制代码

实际上,还有一个状态是跳起来的时候,这时小恐龙是两条腿撑开的:

dino.png

因此,增加一个状态:

if(dino.run){
    if(time%2==0){
        dino.frame='a'
    }
    if(time%4==0){
        dino.frame='b'
    }
}else{
    dino.frame='dino'
}
复制代码

背景滚动

bg.png

背景是一个很长的图。滚动很容易,让它的x轴自减就行了。但不论多长的图,总有滚完的时候。

滚完后,背景就会出现一个空白。

为了让背景不间断,我们用两张一模一样的图,交替滚动。

bgMove(){
    const {bg,speed}=this
    if(bg[0].x<2393){
        bg[0].x-=speed.x
    }
    if(bg[1].x<2393){
        bg[1].x-=speed.x
    }
    if(bg[1].x<=-2393+454 && bg[0].x==2393){
        bg[0].x=454
    }
    if(bg[0].x<=-2393+454 && bg[1].x==2393){
        bg[1].x=454
    }
    if(bg[1].x<=-2393){
        bg[1].x=2393
    }
    if(bg[0].x<=-2393){
        bg[0].x=2393
    }
}
复制代码

上面代码的2393是背景的实际宽度。454是手表屏幕的大小。

仙人掌移动

比背景移动简单多了,直接x轴自减就可以了。

跳跃效果

设置一个y轴的向量

const {y,toY}=this.dino
if(y==toY && y>=300){
    this.dino.toY=this.jump
}
复制代码

在游戏循环中,对y和toY进行操作

if(toY<=y){
    dino.y-=speed.y
    dino.run=false
}
if(y<=jump){
    dino.toY=300
}
if(toY>=y){
    dino.y+=speed.y
    dino.run=true
}
复制代码

碰撞检测

collision_check(){
    const {dino,cactus}=this
    if(dino.x + dino.w > cactus.x && dino.x < cactus.x + cactus.w){
        if(cactus.y + cactus.h > dino.y && cactus.y < dino.y + dino.h){
            this.game_over=true
        }
    }
}
复制代码

源码

最后,源码在 github.com/codetyphon/…

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享