第7讲:以Point、ObservablePoint为例,添加部分功能。

在src/lib中,创建PointUtils.ts

import {IPoint, Point, ObservablePoint} from "pixi.js";

declare module "pixi.js"{
    interface IPoint{
        length(): number;
        add(other: IPoint): Point;
        sub(other: IPoint): Point;
    }
}

Point.prototype.length = function(){
    return Math.sqrt(this.x * this.x + this.y * this.y);
}

Point.prototype.add = function(other: IPoint){
    return new Point(this.x + other.x, this.y + other.y);
}

Point.prototype.sub = function(other: IPoint){
    return new Point(this.x - other.x, this.y - other.y);
}

ObservablePoint.prototype.length = Point.prototype.length;
ObservablePoint.prototype.add = Point.prototype.add;
ObservablePoint.prototype.sub = Point.prototype.sub;

其中,Point.prototype.add = function(other: IPoint){
return new Point(this.x + other.x, this.y + other.y);
}
就是往Point类中自己添加了add方法。
ObservablePoint也是IPoint的实现,所以新增的方法与Point一样。故直接赋值即可:
ObservablePoint.prototype.add = Point.prototype.add;

在AddChangeFunction.ts中编写代码测试代码。

import {Point, Rectangle, ObservablePoint} from  "pixi.js";
import './lib/RectUtils.ts'
import './lib/PointUtils.ts'

let rect = new Rectangle(0,1,98,99);
let smallRect = new Rectangle(10,11,20,21);
console.log(rect.x);  // 左上角的x = 0
console.log(rect.y);  // 左上角的y = 1
console.log(rect.right); // 右下角x = 98
console.log(rect.bottom); // 右下角y = 99

let res = rect.containsRect(smallRect);
console.log(res);

let pnt0 = new Point(2,5);
console.log(pnt0.length());

function changePointCallback(x: number, y: number): void{
    console.log('point change to : ('+ x + ',' + y + ')');
}

function setPoint(obPnt: ObservablePoint, x: number, y: number)  {
    obPnt.set(x, y);
}

let obPnt = new ObservablePoint(()=>{changePointCallback(obPnt.x, obPnt.y);}, null, 1,2);
let i = 0

let itvl = setInterval(()=>{
    setPoint(obPnt, i, i+1);
    if (i > 16){
        clearInterval(itvl);
    }
    ++i;
}, 500);


其中,ObservablePoint是使用很频繁的类,Point的位置一旦发生改变,触发回调changePointCallback。
setInterval是常用的定时器,每隔500毫秒执行一次函数,执行超过一定次数,结束定时器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值