当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 实现抖音小游戏潜艇大挑战的思路详解

Android 实现抖音小游戏潜艇大挑战的思路详解

2020年06月23日  | 移动技术网移动技术  | 我要评论

《潜水艇大挑战》是抖音上的一款小游戏,以面部识别来驱动潜艇通过障碍物,最近特别火爆,相信很多人都玩过。

一时兴起自己用android自定义view也撸了一个,发现只要有好的创意,不用高深的技术照样可以开发出好玩的应用。开发过程现拿出来与大家分享一下。

项目地址:

基本思路

整个游戏视图可以分成三层:

  • camera(相机):处理相机的preview以及人脸识别
  • background(后景):处理障碍物相关逻辑
  • foreground(前景):处理潜艇相关

在这里插入图片描述

代码也是按上面三个层面组织的,游戏界面的布局可以简单理解为三层视图的叠加,然后在各层视图中完成相关工作

<framelayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <!-- 相机 -->
 <textureview
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>

 <!-- 后景 -->
 <com.my.ugame.bg.backgroundview
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>
 
 <!-- 前景 -->
 <com.my.ugame.fg.foregroundview
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>

</framelayout>

开发中会涉及以下技术的使用,没有高精尖、都是大路货:

  • 相机:使用camera2完成相机的预览和人脸识别
  • 自定义view:定义并控制障碍物和潜艇
  • 属性动画:控制障碍物和潜艇的移动及各种动效

少啰嗦,先看东西!下面介绍各部分代码的实现。

后景(background)bar

首先定义障碍物基类bar,主要负责是将bitmap资源绘制到指定区域。由于障碍物从屏幕右侧定时刷新时的高度随机,所以其绘制区域的x、y、w、h需要动态设置

/**
 * 障碍物基类
 */
sealed class bar(context: context) {

 protected open val bmp = context.getdrawable(r.mipmap.bar)!!.tobitmap()

 protected abstract val srcrect: rect

 private lateinit var dstrect: rect

 private val paint = paint()

 var h = 0f
 set(value) {
  field = value
  dstrect = rect(0, 0, w.toint(), h.toint())
 }

 var w = 0f
 set(value) {
  field = value
  dstrect = rect(0, 0, w.toint(), h.toint())
 }

 var x = 0f
 set(value) {
  view.x = value
  field = value
 }

 val y
 get() = view.y

 internal val view by lazy {
 barview(context) {
  it?.apply {
  drawbitmap(
   bmp,
   srcrect,
   dstrect,
   paint
  )
  }
 }
 }

}

internal class barview(context: context?, private val block: (canvas?) -> unit) :
 view(context) {

 override fun ondraw(canvas: canvas?) {
 block((canvas))
 }
}

障碍物分为上方和下方两种,由于使用了同一张资源,所以绘制时要区别对待,因此定义了两个子类:upbardnbar

/**
 * 屏幕上方障碍物
 */
class upbar(context: context, container: viewgroup) : bar(context) {

 private val _srcrect by lazy(lazythreadsafetymode.none) {
 rect(0, (bmp.height * (1 - (h / container.height))).toint(), bmp.width, bmp.height)
 }
 override val srcrect: rect
 get() = _srcrect
}

下方障碍物的资源旋转180度后绘制

/**
 * 屏幕下方障碍物
 */
class dnbar(context: context, container: viewgroup) : bar(context) {

 override val bmp = super.bmp.let {
 bitmap.createbitmap(
  it, 0, 0, it.width, it.height,
  matrix().apply { postrotate(-180f) }, true
 )
 }

 private val _srcrect by lazy(lazythreadsafetymode.none) {
 rect(0, 0, bmp.width, (bmp.height * (h / container.height)).toint())
 }

 override val srcrect: rect
 get() = _srcrect
}

backgroundview

接下来创建后景的容器backgroundview,容器用来定时地创建、并移动障碍物。
通过列表barslist管理当前所有的障碍物,onlayout中,将障碍物分别布局到屏幕上方和下方

/**
 * 后景容器类
 */
class backgroundview(context: context, attrs: attributeset?) : framelayout(context, attrs) {

 internal val barslist = mutablelistof<bars>()

 override fun onlayout(changed: boolean, left: int, top: int, right: int, bottom: int) {
 barslist.flatmap { listof(it.up, it.down) }.foreach {
  val w = it.view.measuredwidth
  val h = it.view.measuredheight
  when (it) {
  is upbar -> it.view.layout(0, 0, w, h)
  else -> it.view.layout(0, height - h, w, height)
  }
 }
 }

提供两个方法startstop,控制游戏的开始和结束:

  • 游戏结束时,要求所有障碍物停止移动。
  • 游戏开始后会通过timer,定时刷新障碍物
/**
 * 游戏结束,停止所有障碍物的移动
 */
 @uithread
 fun stop() {
 _timer.cancel()
 _anims.foreach { it.cancel() }
 _anims.clear()
 }

 /**
 * 定时刷新障碍物:
 * 1. 创建
 * 2. 添加到视图
 * 3. 移动
 */
 @uithread
 fun start() {
 _clearbars()
 timer().also { _timer = it }.schedule(object : timertask() {
  override fun run() {
  post {
   _createbars(context, barslist.lastornull()).let {
   _addbars(it)
   _movebars(it)
   }
  }
  }

 }, first_appear_delay_millis, bar_appear_interval_millis
 )
 }

 /**
 * 游戏重启时,清空障碍物
 */
 private fun _clearbars() {
 barslist.clear()
 removeallviews()
 }

刷新障碍物

障碍物的刷新经历三个步骤:

  • 创建:上下两个为一组创建障碍物
  • 添加:将对象添加到barslist,同时将view添加到容器
  • 移动:通过属性动画从右侧移动到左侧,并在移出屏幕后删除

创建障碍物时会为其设置随机高度,随机不能太过,要以前一个障碍物为基础进行适当调整,保证随机的同时兼具连贯性

 /**
 * 创建障碍物(上下两个为一组)
 */
 private fun _createbars(context: context, pre: bars?) = run {
 val up = upbar(context, this).apply {
  h = pre?.let {
  val step = when {
   it.up.h >= height - _gap - _step -> -_step
   it.up.h <= _step -> _step
   _random.nextboolean() -> _step
   else -> -_step
  }
  it.up.h + step
  } ?: _barheight
  w = _barwidth
 }

 val down = dnbar(context, this).apply {
  h = height - up.h - _gap
  w = _barwidth
 }

 bars(up, down)

 }

 /**
 * 添加到屏幕
 */
 private fun _addbars(bars: bars) {
 barslist.add(bars)
 bars.asarray().foreach {
  addview(
  it.view,
  viewgroup.layoutparams(
   it.w.toint(),
   it.h.toint()
  )
  )
 }
 }

 /**
 * 使用属性动画移动障碍物
 */
 private fun _movebars(bars: bars) {
 _anims.add(
  valueanimator.offloat(width.tofloat(), -_barwidth)
  .apply {
   addupdatelistener {
   bars.asarray().foreach { bar ->
    bar.x = it.animatedvalue as float
    if (bar.x + bar.w <= 0) {
    post { removeview(bar.view) }
    }
   }
   }

   duration = bar_move_duration_millis
   interpolator = linearinterpolator()
   start()
  })
 }

}

前景(foreground)

boat

定会潜艇类boat,创建自定义view,并提供方法移动到指定坐标

/**
 * 潜艇类
 */
class boat(context: context) {

 internal val view by lazy { boatview(context) }

 val h
 get() = view.height.tofloat()

 val w
 get() = view.width.tofloat()

 val x
 get() = view.x

 val y
 get() = view.y

 /**
 * 移动到指定坐标
 */
 fun moveto(x: int, y: int) {
 view.smoothmoveto(x, y)
 }

}

boatview

自定义view中完成以下几个事情

  • 通过两个资源定时切换,实现探照灯闪烁的效果
  • 通过overscroller让移动过程更加顺滑
  • 通过一个rotation animation,让潜艇在移动时可以调转角度,更加灵动
internal class boatview(context: context?) : appcompatimageview(context) {

 private val _scroller by lazy { overscroller(context) }

 private val _res = arrayof(
 r.mipmap.boat_000,
 r.mipmap.boat_002
 )

 private var _rotationanimator: objectanimator? = null

 private var _cnt = 0
 set(value) {
  field = if (value > 1) 0 else value
 }

 init {
 scaletype = scaletype.fit_center
 _startflashing()
 }

 private fun _startflashing() {
 postdelayed({
  setimageresource(_res[_cnt++])
  _startflashing()
 }, 500)
 }

 override fun computescroll() {
 super.computescroll()

 if (_scroller.computescrolloffset()) {

  x = _scroller.currx.tofloat()
  y = _scroller.curry.tofloat()

  // keep on drawing until the animation has finished.
  postinvalidateonanimation()
 }

 }

 /**
 * 移动更加顺换
 */
 internal fun smoothmoveto(x: int, y: int) {
 if (!_scroller.isfinished) _scroller.abortanimation()
 _rotationanimator?.let { if (it.isrunning) it.cancel() }

 val curx = this.x.toint()
 val cury = this.y.toint()

 val dx = (x - curx)
 val dy = (y - cury)
 _scroller.startscroll(curx, cury, dx, dy, 250)

 _rotationanimator = objectanimator.offloat(
  this,
  "rotation",
  rotation,
  math.todegrees(atan((dy / 100.todouble()))).tofloat()
 ).apply {
  duration = 100
  start()
 }

 postinvalidateonanimation()
 }
}

foregroundview

  • 通过boat成员持有潜艇对象,并对其进行控制
  • 实现camerahelper.facedetectlistener根据人脸识别的回调,移动潜艇到指定位置
  • 游戏开始时,创建潜艇并做开场动画
/**
 * 前景容器类
 */
class foregroundview(context: context, attrs: attributeset?) : framelayout(context, attrs),
 camerahelper.facedetectlistener {

 private var _isstop: boolean = false

 internal var boat: boat? = null

 /**
 * 游戏停止,潜艇不再移动
 */
 @mainthread
 fun stop() {
 _isstop = true
 }
 
 /**
 * 接受人脸识别的回调,移动位置
 */
 override fun onfacedetect(faces: array<face>, facesrect: arraylist<rectf>) {
 if (_isstop) return
 if (facesrect.isnotempty()) {
  boat?.run {
  val face = facesrect.first()
  val x = (face.left - _widthoffset).toint()
  val y = (face.top + _heightoffset).toint()
  moveto(x, y)
  }
  _face = facesrect.first()
 }
 }

}

开场动画

游戏开始时,将潜艇通过动画移动到起始位置,即y轴的二分之一处

 /**
 * 游戏开始时通过动画进入
 */
 @mainthread
 fun start() {
 _isstop = false
 if (boat == null) {
  boat = boat(context).also {
  post {
   addview(it.view, _width, _width)
   animatorset().apply {
   play(
    objectanimator.offloat(
    it.view,
    "y",
    0f,
    this@foregroundview.height / 2f
    )
   ).with(
    objectanimator.offloat(it.view, "rotation", 0f, 360f)
   )
   doonend { _ -> it.view.rotation = 0f }
   duration = 1000
   }.start()
  }
  }
 }
 }

相机(camera)

相机部分主要有textureviewcamerahelper组成。textureview提供给camera承载preview;工具类camerahelper主要完成以下功能:

  • 开启相机:通过cameramanger代开摄像头
  • 摄像头切换:切换前后置摄像头,
  • 预览:获取camera提供的可预览尺寸,并适配textureview显示
  • 人脸识别:检测人脸位置,进行testureview上的坐标变换

相机硬件提供的可预览尺寸与屏幕实际尺寸(即textureview尺寸)可能不一致,所以需要在相机初始化时,选取最合适的previewsize,避免textureview上发生画面拉伸等异常

class camerahelper(val mactivity: activity, private val mtextureview: textureview) {

 private lateinit var mcameramanager: cameramanager
 private var mcameradevice: cameradevice? = null
 private var mcameracapturesession: cameracapturesession? = null

 private var canexchangecamera = false      //是否可以切换摄像头
 private var mfacedetectmatrix = matrix()      //人脸检测坐标转换矩阵
 private var mfacesrect = arraylist<rectf>()      //保存人脸坐标信息
 private var mfacedetectlistener: facedetectlistener? = null    //人脸检测回调
 private lateinit var mpreviewsize: size

 /**
 * 初始化
 */
 private fun initcamerainfo() {
 mcameramanager = mactivity.getsystemservice(context.camera_service) as cameramanager
 val cameraidlist = mcameramanager.cameraidlist
 if (cameraidlist.isempty()) {
  mactivity.toast("没有可用相机")
  return
 }

 //获取摄像头方向
 mcamerasensororientation =
  mcameracharacteristics.get(cameracharacteristics.sensor_orientation)!!
 //获取streamconfigurationmap,它是管理摄像头支持的所有输出格式和尺寸
 val configurationmap =
  mcameracharacteristics.get(cameracharacteristics.scaler_stream_configuration_map)!!

 val previewsize = configurationmap.getoutputsizes(surfacetexture::class.java) //预览尺寸

 // 当屏幕为垂直的时候需要把宽高值进行调换,保证宽大于高
 mpreviewsize = getbestsize(
  mtextureview.height,
  mtextureview.width,
  previewsize.tolist()
 )

 //根据preview的size设置textureview
 mtextureview.surfacetexture.setdefaultbuffersize(mpreviewsize.width, mpreviewsize.height)
 mtextureview.setaspectratio(mpreviewsize.height, mpreviewsize.width)
 }

选取preview尺寸的原则与textureview的长宽比尽量一致,且面积尽量接近。

private fun getbestsize(
 targetwidth: int,
 targetheight: int,
 sizelist: list<size>
 ): size {
 val bigenough = arraylist<size>() //比指定宽高大的size列表
 val notbigenough = arraylist<size>() //比指定宽高小的size列表

 for (size in sizelist) {

  //宽高比 == 目标值宽高比
  if (size.width == size.height * targetwidth / targetheight
  ) {
  if (size.width >= targetwidth && size.height >= targetheight)
   bigenough.add(size)
  else
   notbigenough.add(size)
  }
 }

 //选择bigenough中最小的值 或 notbigenough中最大的值
 return when {
  bigenough.size > 0 -> collections.min(bigenough, comparesizesbyarea())
  notbigenough.size > 0 -> collections.max(notbigenough, comparesizesbyarea())
  else -> sizelist[0]
 }
		
		initfacedetect()
 }

initfacedetect()用来进行人脸的matrix初始化,后文介绍

人脸识别

为相机预览,创建一个cameracapturesession对象,会话通过cameracapturesession.capturecallback返回totalcaptureresult,通过参数可以让其中包括人脸识别的相关信息

 /**
 * 创建预览会话
 */
 private fun createcapturesession(cameradevice: cameradevice) {

 // 为相机预览,创建一个cameracapturesession对象
 cameradevice.createcapturesession(
  arraylistof(surface),
  object : cameracapturesession.statecallback() {

  override fun onconfigured(session: cameracapturesession) {
   mcameracapturesession = session
   session.setrepeatingrequest(
   capturerequestbuilder.build(),
   mcapturecallback,
   mcamerahandler
   )
  }

  },
  mcamerahandler
 )
 }

 private val mcapturecallback = object : cameracapturesession.capturecallback() {
 override fun oncapturecompleted(
  session: cameracapturesession,
  request: capturerequest,
  result: totalcaptureresult
 ) {
  super.oncapturecompleted(session, request, result)
  if (mfacedetectmode != capturerequest.statistics_face_detect_mode_off)
  handlefaces(result)

 }
 }

通过mfacedetectmatrix对人脸信息进行矩阵变化,确定人脸坐标以使其准确应用到textureview。

 /**
 * 处理人脸信息
 */
 private fun handlefaces(result: totalcaptureresult) {
 val faces = result.get(captureresult.statistics_faces)!!
 mfacesrect.clear()

 for (face in faces) {
  val bounds = face.bounds

  val left = bounds.left
  val top = bounds.top
  val right = bounds.right
  val bottom = bounds.bottom

  val rawfacerect =
  rectf(left.tofloat(), top.tofloat(), right.tofloat(), bottom.tofloat())
  mfacedetectmatrix.maprect(rawfacerect)

  var resultfacerect = if (mcamerafacing == capturerequest.lens_facing_front) {
  rawfacerect
  } else {
  rectf(
   rawfacerect.left,
   rawfacerect.top - mpreviewsize.width,
   rawfacerect.right,
   rawfacerect.bottom - mpreviewsize.width
  )
  }

  mfacesrect.add(resultfacerect)

 }
 
 		mactivity.runonuithread {
  mfacedetectlistener?.onfacedetect(faces, mfacesrect)
 }
 }

最后,在ui线程将包含人脸坐标的rect通过回调传出:

mactivity.runonuithread {
 mfacedetectlistener?.onfacedetect(faces, mfacesrect)
 }

facedetectmatrix

mfacedetectmatrix是在获取previewsize之后创建的

 /**
 * 初始化人脸检测相关信息
 */
 private fun initfacedetect() {

 val facedetectmodes =
  mcameracharacteristics.get(cameracharacteristics.statistics_info_available_face_detect_modes) //人脸检测的模式

 mfacedetectmode = when {
  facedetectmodes!!.contains(capturerequest.statistics_face_detect_mode_full) -> capturerequest.statistics_face_detect_mode_full
  facedetectmodes!!.contains(capturerequest.statistics_face_detect_mode_simple) -> capturerequest.statistics_face_detect_mode_full
  else -> capturerequest.statistics_face_detect_mode_off
 }

 if (mfacedetectmode == capturerequest.statistics_face_detect_mode_off) {
  mactivity.toast("相机硬件不支持人脸检测")
  return
 }

 val activearraysizerect =
  mcameracharacteristics.get(cameracharacteristics.sensor_info_active_array_size)!! //获取成像区域
 val scaledwidth = mpreviewsize.width / activearraysizerect.width().tofloat()
 val scaledheight = mpreviewsize.height / activearraysizerect.height().tofloat()

 val mirror = mcamerafacing == cameracharacteristics.lens_facing_front

 mfacedetectmatrix.setrotate(mcamerasensororientation.tofloat())
 mfacedetectmatrix.postscale(if (mirror) -scaledheight else scaledheight, scaledwidth)// 注意交换width和height的位置!
 mfacedetectmatrix.posttranslate(
  mpreviewsize.height.tofloat(),
  mpreviewsize.width.tofloat()
 )

 }

控制类(gamecontroller)

三大视图层组装完毕,最后需要一个总控类,对游戏进行逻辑控制

gamecontroller

主要完成以下工作:

  • 控制游戏的开启/停止
  • 计算游戏的当前得分
  • 检测潜艇的碰撞
  • 对外(activity或者fragment等)提供游戏状态监听的接口

游戏开始时进行相机的初始化,创建gamehelper类并建立setfacedetectlistener回调到foregroundview

class gamecontroller(
 private val activity: appcompatactivity,
 private val textureview: autofittextureview,
 private val bg: backgroundview,
 private val fg: foregroundview
) {
 
 private var camera2helperface: camerahelper? = null
 /**
 * 相机初始化
 */
 private fun initcamera() {
 camerahelper ?: run {
  camerahelper = camerahelper(activity, textureview).apply {
  setfacedetectlistener(object : camerahelper.facedetectlistener {
   override fun onfacedetect(faces: array<face>, facesrect: arraylist<rectf>) {
   if (facesrect.isnotempty()) {
    fg.onfacedetect(faces, facesrect)
   }
   }
  })
  }
 }
 }

游戏状态

定义gamestate,对外提供状态的监听。目前支持三种状态

  • start:游戏开始
  • over:游戏结束
  • score:游戏得分
sealed class gamestate(open val score: long) {
 object start : gamestate(0)
 data class over(override val score: long) : gamestate(score)
 data class score(override val score: long) : gamestate(score)
}

可以在stop、start的时候,更新状态

/**
 * 游戏状态
 */
 private val _state = mutablelivedata<gamestate>()
 internal val gamestate: livedata<gamestate>
 get() = _state

 /**
 * 游戏停止
 */
 fun stop() {
 bg.stop()
 fg.stop()
 _state.value = gamestate.over(_score)
 _score = 0l
 }

 /**
 * 游戏再开
 */
 fun start() {
 initcamera()
 fg.start()
 bg.start()
 _state.value = gamestate.start
 handler.postdelayed({
  startscoring()
 }, first_appear_delay_millis)
 }

计算得分

游戏启动时通过startscoring开始计算得分并通过gamestate上报。
目前的规则设置很简单,存活时间即游戏得分

 /**
 * 开始计分
 */
 private fun startscoring() {
 handler.postdelayed(
  {
  fg.boat?.run {
   bg.barslist.flatmap { listof(it.up, it.down) }
   .foreach { bar ->
    if (iscollision(
     bar.x, bar.y, bar.w, bar.h,
     this.x, this.y, this.w, this.h
    )
    ) {
    stop()
    return@postdelayed
    }
   }
  }
  _score++
  _state.value = gamestate.score(_score)
  startscoring()
  }, 100
 )
 }

检测碰撞

iscollision根据潜艇和障碍物当前位置,计算是否发生了碰撞,发生碰撞则gameover

/**
 * 碰撞检测
 */
 private fun iscollision(
 x1: float,
 y1: float,
 w1: float,
 h1: float,
 x2: float,
 y2: float,
 w2: float,
 h2: float
 ): boolean {
 if (x1 > x2 + w2 || x1 + w1 < x2 || y1 > y2 + h2 || y1 + h1 < y2) {
  return false
 }
 return true
 }

activity

activity的工作简单:

  • 权限申请:动态申请camera权限
  • 监听游戏状态:创建gamecontroller,并监听gamestate状态
private fun startgame() {
 permissionutils.checkpermission(this, runnable {
  gamecontroller.start()
  gamecontroller.gamestate.observe(this, observer {
  when (it) {
   is gamestate.start ->
   score.text = "danger\nahead"
   is gamestate.score ->
   score.text = "${it.score / 10f} m"
   is gamestate.over ->
   alertdialog.builder(this)
    .setmessage("游戏结束!成功推进 ${it.score / 10f} 米! ")
    .setnegativebutton("结束游戏") { _: dialoginterface, _: int ->
    finish()
    }.setcancelable(false)
    .setpositivebutton("再来一把") { _: dialoginterface, _: int ->
    gamecontroller.start()
    }.show()
  }
  })
 })
 }

最后

在这里插入图片描述

项目结构很清晰,用到的大都是常规技术,即使是新入坑android的同学看起来也不费力。在现有基础上还可以通过添加bgm、增加障碍物种类等,进一步提高游戏性。喜欢的话留个star鼓励一下作者吧 ^^

到此这篇关于android 实现抖音小游戏潜艇大挑战的思路详解的文章就介绍到这了,更多相关android 抖音游戏潜艇大挑战内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网