IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 微信小程序|飞翔的圣诞老人 -> 正文阅读

[移动开发]微信小程序|飞翔的圣诞老人

一、前言

2022年圣诞节即将到来啦,很高兴这次我们又能一起度过~
此篇文章主要使用小程序实现飞翔的圣诞老人,跟随文章步骤带着圣诞老人翻越障碍一起去送礼物吧。

在这里插入图片描述
在这里插入图片描述

二、实现步骤

2.1、创建小程序

  1. 访问微信公众平台,点击账号注册。

在这里插入图片描述

  1. 选择小程序,并在表单填写所需的各项信息进行注册。

在这里插入图片描述
在这里插入图片描述

  1. 在开发管理选择开发设置,将AppID及AppSecret复制出来进行存储。

在这里插入图片描述

  1. 下载安装微信web开发者工具并创建一个新的项目,填入上图所复制的AppId。

在这里插入图片描述
在这里插入图片描述

2.2、游戏页

  1. 准备圣诞老人素材图片的同时在index页面中实现一个canvas标签,效果主要通过此标签进行实现。

在这里插入图片描述

在这里插入图片描述

<view>
  <canvas canvas-id="1"/>
</view>
  1. 定义一个按钮用于控制圣诞老人升降,同时根据游戏状态显示不同的文字。

在这里插入图片描述
在这里插入图片描述

  <button id="flyButton" type="primary" bindtouchstart="handleTouchStart" bindtouchend="handleTouchEnd"> 
    {{status===0?'开始游戏':''}}
    {{status===1?'点击起飞':''}}
    {{status===2?'重新挑战':''}}
  </button>
  1. 在index.js中获取屏幕宽高信息并作用到canvas标签。

在这里插入图片描述

  onReady: function (e) {
    let gameConfig = { statusCallback: this.changeStatus };
    let that = this;

    // 获取屏幕的宽高信息
    wx.getSystemInfo({
      success: function (res) {
        //console.debug('screen width = %d, height = %d', res.windowWidth, res.windowHeight);
        gameConfig.canvasWidth = res.windowWidth;
        gameConfig.canvasHeight = res.windowHeight / 2;
      },
      complete: function () {
        let game = new Game(gameConfig);
        that.game = game;
      }
    });
  },
  1. 对页面上的按钮点击及放开事件进行处理。

在这里插入图片描述

  // 处理按钮按下的事件
  handleTouchStart: function (event) {
    if (this.data.status == 1)
      this.game.up();
  },

  // 处理按钮放开的事件
  handleTouchEnd: function (event) {
    if (this.data.status == 0)
      this.game.start();
    else if (this.data.status == 1)
      this.game.down();
    else if (this.data.status == 2)
      this.game.start();
  }
  1. 定义构造函数在canvas上绘制图形。

在这里插入图片描述

在这里插入图片描述

  1. 计算组件新的位置,每一帧都要重新计算一次
    newPos() {
        // console.log('xSpeed=%d, ySpeed=%d, xAcc=%d, yAcc=%d', this.xSpeed, this.ySpeed, this.xAcc, this.yAcc);
        // 首先计算新的速度
        this.xSpeed += this.xAcc;
        this.ySpeed += this.yAcc;
        // 计算新的位置
        this.x += this.xSpeed;
        this.y += this.ySpeed;
        // 检测是否碰到了canvas边缘
        this.hitBoundary();
    }
  1. 检测组件是否碰到了canvas边缘
    hitBoundary() {
        if (this.y < 0) {
            this.y = 0;
            this.ySpeed = 0;
            if (this.yAcc < 0) {
                this.yAcc = 0;
            }
        }

        let bottom = this.y + this.height;
        if (bottom > this.canvasHeight) {
            this.y = this.canvasHeight - this.height;
            this.ySpeed = 0;
            if (this.yAcc > 0) {
                this.yAcc = 0;
            }
        }
    }
  1. 检测是否撞到了障碍物
   crashWith(otherobj) {
        let myleft = this.x;
        let myright = this.x + (this.width);
        let mytop = this.y;
        let mybottom = this.y + (this.height);
        let otherleft = otherobj.x;
        let otherright = otherobj.x + (otherobj.width);
        let othertop = otherobj.y;
        let otherbottom = otherobj.y + (otherobj.height);
        let crash = true;

        if (this.type == 'bird') {
            myleft += 5;
            myright -= 5;
            mytop += 5;
            mybottom -= 5;
        }

        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
  1. 在index这个page下新建一个game.js,对canvas进行定义。

在这里插入图片描述

  1. 实现canvas绘制随机生成障碍物。

在这里插入图片描述

        // 第一步,帧数++
        this.frameCount++;
        this.score.text = '分数: ' + this.frameCount;

        // 第二步,随机生成障碍物
        // 每隔固定帧数就生成一个障碍物
        if (this.frameCount % 13 == 0) {
            let x = this.canvasWidth;  // 从x轴的哪里开始绘制
            let minHeight = 20, maxHeight = 200;  // 障碍物的高度限制
            let trueHeight = Math.floor(Math.random() * (maxHeight - minHeight + 1) + minHeight);
            let minGap = 50, maxGap = 200;  // 空隙的大小
            let trueGap = Math.floor(Math.random() * (maxGap - minGap + 1) + minGap);
            // 障碍物的宽度都是10,注意给它们相同的x轴上的速度
            this.obstacles.push(new Component({ x: x, y: 0, width: 10, height: trueHeight, xSpeed: -10, context: this.ctx }));
            this.obstacles.push(new Component({ x: x, y: trueHeight + trueGap, width: 10, height: this.canvasHeight - trueHeight - trueGap, xSpeed: -10, context: this.ctx }));
        }
  1. 判断圣诞老人是否碰撞到了障碍物,并停止游戏。

在这里插入图片描述

 for (let obstacle of this.obstacles) {
     if (this.role.crashWith(obstacle)) {
         this.stop();  // 撞到障碍物就停止游戏
         break;
     }
 }
  1. 将玩家分数通过接口或者云函数的方式提交后在排行榜页面进行展示。

在这里插入图片描述

    /**
     * 向服务端汇报数据
     */
    sendRecord() {
        const app = getApp();
        const that = this;
        app.getUserInfo(function (userInfo) {
            const record = {
                name: userInfo.nickName,
                pic: userInfo.avatarUrl,
                score: that.frameCount
            };
            console.debug('send record to server: %o', record);
            wx.request({
                url: config.host + '/flappy/send',  // 注意只能请求公众平台中配置好的域名
                data: record,
                method: 'POST'
            });
        });
    }

2.3、排行榜

  1. 新建一个排行榜页面,上面放几个view,能将用户头像、昵称、分数等信息展示出来就行。

在这里插入图片描述

  1. 准备一些排行榜图片素材,也可以直接通过css来实现。

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  1. 通过云函数或者请求接口的方式读取数据

在这里插入图片描述

    const that = this;
    wx.request({
      url: '接口地址',
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 200) {
          that.setData({
            listData: res.data
          });
        } else {
          that.handleError();
        }
      },
      fail: function () {
        that.handleError();
      }
    });
  1. 将接口数据渲染到界面如下图。

在这里插入图片描述

  <!-- list内容 -->
        <block wx:for="{{listData}}">
          <view class="list-item">
            <view class="avatar-wrapper">
                <image class="avatar" wx:if="{{item.pic!=undefined}}"  src="{{item.pic}}"></image>
            </view>
            <text class="title">{{item.name}}</text>
            <text class="sub-title">分数:{{item.score}}</text>
            <image class="rank-img" wx:if="{{index==0}}" src="../../images/rank1.png"></image>
            <image class="rank-img" wx:if="{{index==1}}" src="../../images/rank2.png"></image>
            <image class="rank-img" wx:if="{{index==2}}" src="../../images/rank3.png"></image>
          </view>
        </block>

三、代码块

<view>
  <canvas canvas-id="1"/>
  <button id="flyButton" type="primary" bindtouchstart="handleTouchStart" bindtouchend="handleTouchEnd"> 
    {{status===0?'开始游戏':''}}
    {{status===1?'点击起飞':''}}
    {{status===2?'重新挑战':''}}
  </button>
</view>
// pages/list/index.js
Page({
  data: {
    listData: []  // 排行榜数据,包括:用户名/头像/分数,没有头像就显示默认头像
  },

  /**
   * 设置当前页面标题
   */
  setTitle: function () {
    wx.setNavigationBarTitle({
      title: 'Top20达人榜'
    });
  },

  /**
   * 获取排行榜数据
   */
  getList: function () {
    const that = this;
    wx.request({
      url: '接口地址',
      method: 'GET',
      success: function (res) {
        if (res.statusCode == 200) {
          that.setData({
            listData: res.data
          });
        } else {
          that.handleError();
        }
      },
      fail: function () {
        that.handleError();
      }
    });
  },

  /**
   * 处理请求后端接口出错的情况
   */
  handleError: function () {
    this.setData({
      listData: [{ name: '飞翔的圣诞老人', score: 0 }]
    });
  },


})

四、canvas介绍

  1. 什么是canvas
    canvas 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成,canvas 标签只是图形容器,您必须使用脚本来绘制图形。你可以通过多种方法使用 canvas 绘制路径,盒、圆、字符以及添加图像。
  1. 如何创建canvas
    一个画布在网页中是一个矩形框,通过 canvas元素来绘制注意: 默认情况下 canvas>元素没有边框和内容。
  1. 使用JavaScript来绘制图像
    canvas 元素本身是没有绘图能力的。所有的绘制工作必须在 JavaScript 内部完成:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
  1. canvas坐标
    canvas 是一个二维网格。canvas 的左上角坐标为 (0,0)上面的 fillRect 方法拥有参数 (0,0,150,75)。意思是:在画布上绘制 150x75 的矩形,从左上角开始 (0,0)。
  1. canvas路径
    在Canvas上画线,我们将使用以下两种方法:moveTo(x,y) 定义线条开始坐标、lineTo(x,y) 定义线条结束坐标。绘制线条我们必须使用到 “ink” 的方法,就像stroke().
  1. canvas文本
    使用 canvas 绘制文本,重要的属性和方法如下:font - 定义字体、fillText(text,x,y) - 在 canvas 上绘制实心的文本、strokeText(text,x,y) - 在 canvas 上绘制空心的文本
  1. canvas渐变
    渐变可以填充在矩形, 圆形, 线条, 文本等等, 各种形状可以自己定义不同的颜色。以下有两种不同的方式来设置Canvas渐变:createLinearGradient(x,y,x1,y1) - 创建线条渐变、createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变
  1. canvas图像
    把一幅图像放置到画布上, 使用以下方法:drawImage(image,x,y)
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-12-25 11:21:31  更:2022-12-25 11:24:43 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年3日历 -2024/3/29 17:14:09-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码