import Sprite from '../base/sprite'
import Bullet from './bullet'
import DataBus from '../databus'
import Constants from '../common/constants'
const screenWidth = window.innerWidth
const screenHeight = window.innerHeight
// 玩家相关常量设置
const PLAYER_IMG_SRC = 'images/hero.png'
const PLAYER_WIDTH = 80
const PLAYER_HEIGHT = 80
let databus = new DataBus()
const Config = require('../common/config.js').Config
export default class Player extends Sprite {
constructor() {
super(PLAYER_IMG_SRC, PLAYER_WIDTH, PLAYER_HEIGHT)
// 玩家默认处于屏幕底部居中位置
this.x = screenWidth / 2 - this.width / 2
this.y = screenHeight - this.height - 30
// 用于在手指移动的时候标识手指是否已经在飞机上了
this.touched = false
}
/**
* 当手指触摸屏幕的时候
* 判断手指是否在飞机上
* @param {Number} x: 手指的X轴坐标
* @param {Number} y: 手指的Y轴坐标
* @return {Boolean}: 用于标识手指是否在飞机上的布尔值
*/
checkIsFingerOnAir(x, y) {
const deviation = 30
return !!( x >= this.x - deviation
&& y >= this.y - deviation
&& x <= this.x + this.width + deviation
&& y <= this.y + this.height + deviation )
}
/**
* 根据手指的位置设置飞机的位置
* 保证手指处于飞机中间
* 同时限定飞机的活动范围限制在屏幕中
*/
setAirPosAcrossFingerPosZ(x, y) {
let disX = x - this.width / 2
let disY = y - this.height / 2
if ( disX < 0 )
disX = 0
else if ( disX > screenWidth - this.width )
disX = screenWidth - this.width
if ( disY <= 0 )
disY = 0
else if ( disY > screenHeight - this.height )
disY = screenHeight - this.height
this.x = disX
this.y = disY
}
/**
* 玩家响应手指的触摸事件
* 改变战机的位置
*/
onTouchEvent(type, x, y, callback) {
switch (type){
case 'touchstart':
if (this.checkIsFingerOnAir(x, y)) {
this.touched = true
this.setAirPosAcrossFingerPosZ(x, y)
}
break;
case 'touchmove':
if (this.touched)
this.setAirPosAcrossFingerPosZ(x, y)
break;
case 'touchend':
this.touched = false
break;
}
}
/**
* 玩家射击操作
* 射击时机由外部决定
*/
shoot() {
let bullets = []
let bulletNum = Constants.Bullet.Types.indexOf(Config.Bullet.Type) + 1
for (let i = 0; i < bulletNum; i++)
bullets.push(databus.pool.getItemByClass('bullet', Bullet))
bullets.forEach( (bullet, index) => {
bullet.init(
this.x + this.width * (index+1) / (bulletNum+1) - bullet.width / 2,
this.y - 10,
Config.Bullet.Speed
)
databus.bullets.push(bullet)
})
}
}
|
模板简介:该模板名称为【JavaScript飞机大战小游戏源代码免费下载】,大小是,文档格式为.,推荐使用打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。