效果如下 点击按钮小鱼游动起来
查看需横屏幕
资源如下
小丑鱼可自己选择
背景图
按钮 图片我用的 鸿蒙 图标库 我下载的是一个Svg 就能用 链接:HarmonyOS 主题图标库 | icon素材免费下载 | 华为开发者联盟HarmonyOS 主题图标库 | icon素材免费下载 | 华为开发者联盟https://developer.huawei.com/consumer/cn/design/harmonyos-symbol/
完整代码付下
import matrix4 from '@ohos.matrix4'
interface coordinate {
Px:number|string,
Py:number|string,
rotate:number
}
let ButtonList: coordinate[] = [
{
Px: '50%',
Py: 0,
rotate: -90
},
{
Px: 0,
Py: '50%',
rotate: -180
},
{
Px: '90%',
Py: '50%',
rotate: 0
},
{
Px: '50%',
Py: '90%',
rotate: 90
}
]
interface TranslateNumber {
x:number,
y:number
}
@Entry
@Component
struct Index {
// 小鱼旋转方向
private matrixList =[
matrix4.identity().rotate({ x: 0, y: 0, z: 1, angle: 90 }),//up
matrix4.identity().rotate({ x: 0, y: 1, z: 0, angle: 0}),//left
matrix4.identity().rotate({ x: 0, y:1, z: 0, angle: 180 }),//right
matrix4.identity().rotate({ x: 0, y: 0, z: 1, angle: -90}) //down
]
@State isShowFish:boolean =false //游戏是否开始
@State rotateNum:number =2 //小鱼默认方向
// 小鱼默认位置
@State TranslateP:TranslateNumber ={
x:400,
y:200
}
@Styles transformStyle(){
.transform(this.matrixList[this.rotateNum])
}
// 点击方向按钮
handlerButton=(index:number)=>{
this.rotateNum =index //设置鱼游动方向
switch (index) {
case 0:
this.TranslateP.y -=50
break;
case 1:
this.TranslateP.x -=50
break;
case 2:
this.TranslateP.x +=50
break;
case 3:
this.TranslateP.y +=50
break;
default:
break;
}
}
build() {
Column(){
if(!this.isShowFish){ //判断游戏是否开始
Button('开始游戏',{stateEffect:false})
.width(88)
.height(30)
.fontSize(14)
.backgroundColor('#a4ff13fe')
.position({
top:'50%',
left:'50%'
})
.translate({
x:'-50%',
y:'-50%',
})
.onClick(()=>this.isShowFish=!this.isShowFish)
}else {
Image($r('app.media.fish1'))
.width(80)
.translate({
x:this.TranslateP.x,
y:this.TranslateP.y,
})
// 动画执行时间
.animation({
duration:1000
})
.transformStyle()
Column(){
// 方向按钮
ForEach(ButtonList,(i:coordinate,index:number)=>{
Image($r('app.media.arrow_right'))
.fillColor("#fff")
.width(36)
.borderRadius(18)
.backgroundColor('#66db0cdb')
.position({
x:i.Px,
y:i.Py
})
.rotate({
angle:i.rotate
})
.onClick(()=>{
this.handlerButton(index)
})
})
}
.width(100)
.height(100)
.margin({
top:'15%',
left:'5%'
})
}
}
.backgroundImage($r('app.media.seabed'))
.backgroundImageSize({
width:'100%',
height:'100%'
})
.height('100%')
.width('100%')
.alignItems(HorizontalAlign.Start)
}
}
代码中按钮定位可能不够完美,可使用RelativeContainer组件将按钮元素精准定位
.alignRules({
//底部与父布局底部对齐
bottom: {anchor: "__container__", align: VerticalAlign.Bottom},
//左边与父布局左边对齐
left: {anchor: "__container__", align: HorizontalAlign.Start},
})