在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毫秒执行一次函数,执行超过一定次数,结束定时器。