Spring774
2025-10-30 4d84b498fbb08b9f177b5d9a39e2fedd0522f16f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import Global from "./Global";
 
const { ccclass, property } = cc._decorator;
 
@ccclass
export default class BallRaycast extends cc.Component {
    private static readonly BALL_RADIUS = 4;
    private radius = 1000;
    private remainLength: number;
    private reflectLength = 100;
    private intervalLength: number = 25;
    private ballWidth: number;
 
    private refletTimes: number;
 
    private ctx: cc.Graphics;
    onLoad() {
        this.ctx = this.getComponent(cc.Graphics);
    }
 
    startRaycast(p1: cc.Vec2, direction: cc.Vec2, ballWidth: number) {
        let localPos = p1;// this.node.convertToNodeSpaceAR(p1);
 
        this.refletTimes = 0;
        this.ballWidth = ballWidth;
        let p2 = cc.v2(direction).mul(this.radius).add(localPos);
        this.ctx.clear();
 
        this.remainLength = this.radius;
        this.rayCast(localPos, p2);
    }
 
    rayCast(p1: cc.Vec2, p2: cc.Vec2) {
        let manager = cc.director.getPhysicsManager();
        let results: cc.PhysicsRayCastResult[] = manager.rayCast(p1, p2, cc.RayCastType.All);
        let result = null;
        for (let i of results) {
            //cc.log('i.collider.tag = ' + i.collider.tag);
            if (i.collider.tag == Global.TAG_WALL) {
                result = i;
                break;
            }
        }
 
        if (result) {
            p2 = result.point;
        }
 
        let inVec = p2.sub(p1);
        let lineLength = inVec.mag() - this.ballWidth;
        let pos: cc.Vec2 = cc.v2(this.node.convertToNodeSpaceAR(p1));
        let increment = inVec.normalize().mul(this.intervalLength);
        //只要线段长度还大于每条线段的长度
        for (; lineLength > this.intervalLength; lineLength -= this.intervalLength) {
            //cc.log("add circle");
            pos = pos.add(increment);
            this.ctx.moveTo(pos.x, pos.y)
            this.ctx.circle(pos.x, pos.y, BallRaycast.BALL_RADIUS);
            this.ctx.fill();
        }
 
        if (!result) {
            return;
        }
 
        //cc.log("draw ");
 
        this.remainLength = this.remainLength - inVec.mag();
        this.refletTimes++;
 
        if (this.refletTimes > 1) return;
 
        inVec.normalizeSelf();
        let nor = result.normal;
        let reflectVec = inVec.sub(nor.mul(2 * inVec.dot(nor))).normalize();
 
        p1 = p2.add(nor.mul(this.ballWidth));
 
        pos = this.node.convertToNodeSpaceAR(p1);
        this.ctx.moveTo(pos.x, pos.y)
        this.ctx.circle(pos.x, pos.y, BallRaycast.BALL_RADIUS);
        this.ctx.fill();
 
 
        p2 = reflectVec.mul(this.reflectLength).add(p1);
        this.rayCast(p1, p2);
    }
 
}