HarmonyOS中实现摇杆小球拖动功能

在学习Harmonyos中实现了一个摇杆动画的效果,觉得很不错,特来与诸位分享一下!!!

image.png
摇杆实现
// 摇杆中心区域
  private centerX: number = 120
  private centerY: number = 120

  // 大、小圆半径
  private maxRadius: number = 100
  private radius: number = 20

  // 摇杆小球初始位置
  @State positionX: number = this.centerX
  @State positionY: number = this.centerY

Row() {
          Circle({width: this.maxRadius * 2, height: this.maxRadius * 2})
            .fill('#20101010')
            .position({x: this.centerX - this.maxRadius, y: this.centerY - this.maxRadius})
          Circle({width:this.radius * 2, height: this.radius * 2})
            .fill('#403A3A3A')
            .position({x: this.positionX - this.radius, y: this.positionY - this.radius})
        }
        .height(240)
        .width(240)
        .justifyContent(FlexAlign.Center)
        .position({x: 0, y: 120})
        .onTouch(this.handleTouchEvent.bind(this))
// 处理手指移动的事件
  handleTouchEvent(event:TouchEvent) {
    switch (event.type){
      case TouchType.Up:
        // 还原小鱼速度
        this.speed = 0
        // 取消定时任务
        clearInterval(this.taskId)
        // 还原摇杆小球的坐标
        animateTo(
          {curve: curves.springMotion()},
          () => {
            this.positionX = this.centerX
            this.positionY = this.centerY
            this.angle = 0
          }
        )
        break
      case TouchType.Down:
        // 开始定时任务
        this.taskId = setInterval(() => {
          this.fishX += this.speed * this.cos
          this.fishY += this.speed * this.sin
        }, 40)

        break
      case TouchType.Move:
        // 1. 获取手指位置坐标
        let x = event.touches[0].x
        let y = event.touches[0].y
        // 2. 计算手指与中心点的坐标差值
        let vx = x - this.centerX
        let vy = y - this.centerY
        // 3. 计算手指与中心点连线和x正半轴的夹角,单位是弧度
        let angle = Math.atan2(vy, vx)
        // 4.计算手指与中心点的距离
        let distance = this.getDistance(vx, vy)

        this.sin = Math.sin(angle)
        this.cos = Math.cos(angle)
        animateTo(
          {curve: curves.responsiveSpringMotion()},
          () => {
            // 5. 计算摇杆小球的坐标
            this.positionX = this.centerX + distance * this.cos
            this.positionY = this.centerY + distance * this.sin

            // 6. 修改小球的角度
            if (Math.abs(angle * 2) < Math.PI) {
              this.src = $r('app.media.fish')
            } else {
              this.src = $r('app.media.fish_rev')
              angle = angle < 0 ? angle + Math.PI : angle - Math.PI
            }
            this.angle = angle * 180 / Math.PI
            this.speed = 5
          }
        )
        break
    }
  }

  getDistance(x: number, y: number) {
    let d = Math.sqrt(x * x + y * y)
    return Math.min(d, this.maxRadius)
  }

代码很简单,先是实现了两个同心圆,根据已知的半径,和位置就能实现两个圆,在利用触摸事件,实现摇杆的功能, getDistance 方法是获取两点之间的距离,利用反正切函数的vx和vy获取距离,这就是核心代码,与诸位共勉

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容