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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 05:24:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 05:24:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 05:24:02       58 阅读
  4. Python语言-面向对象

    2024-07-16 05:24:02       69 阅读

热门阅读

  1. 喜欢dp动态规划的第二天(暑假提升)

    2024-07-16 05:24:02       24 阅读
  2. 习题1 回文数 python、C++ 不同解法

    2024-07-16 05:24:02       29 阅读
  3. js的多线程示例

    2024-07-16 05:24:02       26 阅读
  4. 记一次使用vue连接rabbitMq

    2024-07-16 05:24:02       28 阅读
  5. 蓝易云 - 美国云端服务器最低成本方案揭示!

    2024-07-16 05:24:02       24 阅读
  6. vue3 学习笔记10 -- 父子传参

    2024-07-16 05:24:02       26 阅读
  7. 《C++ 入门:第一个小程序》

    2024-07-16 05:24:02       24 阅读