微信小程序

game.js 

import {Sprite} from './wjjs/sprite.js' ;
var canvas=wx.createCanvas()
var ctx = canvas.getContext('2d') 
//var image = wx.createImage()
//image.src = './images/bullet.png';
//image.οnlοad=function(){ctx.drawImage(image,0,0,image.width, image.height, 0, 0, //image.width,image.height,) }
/*
class Sprite {
  constructor(ctx, src) {
    var image = wx.createImage()
    image.src = src;
    image.onload = function () { ctx.drawImage(image, 0, 0, 100, 100) }
  }
 let person = new Sprite(ctx, './images/bullet.png');
 let ss = new Sprite(ctx, './images/enemy.png');
}*/
//初始化
var zhenlv=30
var mouse_x=0
var mouse_y=0
 
let zidan = Sprite.create( ctx, './images/bullet.png',0,0,10,10,1001)
let kuai = Sprite.create(ctx, './images/enemy.png', 220, 220, 30, 30, 1002)
let ban = Sprite.create(ctx, './images/enemy.png', 220, 220, 30, 30, 1003)
//觸摸事件
wx.onTouchMove(function (res) {
  mouse_x = res.changedTouches[0].clientX // 重新判斷當前觸摸點x座標
  mouse_y = res.changedTouches[0].clientY // 重新判斷當前觸摸點y座標
})


//循環加載
const { windowWidth, windowHeight } = wx.getSystemInfoSync()
 
setInterval(function () {
  ctx.clearRect(0, 0, windowWidth, windowHeight)
  /**********更新座標*******/
  //person.x=mouse_x
  //person.y=mouse_y
  /*******繪製事件 *****/
  zidan.draw(ctx)
  kuai.draw(ctx)
  //ban.draw(ctx)
  /******判斷碰撞********/
  //if (person.isCollideWith(di)){console.log(person.isCollideWith(di))}



}, 1000/zhenlv)
 

 

 

 
 

sprite.js 


export class Sprite {
  constructor(ctx, src, x=0, y=0, wight=100, height=100,id) {

    this.image = wx.createImage()
    this.image.src = src;
    this.wight = wight
    this.height = height
    this.x=x
    this.y=y
    this.ctx = ctx
    this.visible = true
    this.id=id

  }

  static create(ctx, src, x, y, wight, height, id) {
    return new Sprite(ctx, src,x, y, wight, height, id);
  }
  /****繪製方法 */
  draw(ctx){
    if (this.visible = true) { ctx.drawImage(this.image, this.x, this.y, this.wight, this.height) }
  }
  /*****碰撞方法 */
  isCollideWith(sp) {
    let spX = sp.x + sp.wight / 2
    let spY = sp.y + sp.height / 2
     
    if (!this.visible || !sp.visible)
      return false

    return !!(spX >= this.x
      && spX <= this.x + this.wight
      && spY >= this.y
      && spY <= this.y + this.height)
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章