/
Scroller.ts
62 lines (53 loc) · 2.15 KB
/
Scroller.ts
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
import { _decorator, Component, Node, Vec3, UITransform, instantiate, Vec2, math, Sprite } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('Scroller')
export class Scroller extends Component {
nodeHeight: number = 0;
bottomNode: Node = null;
upperNode: Node = null;
topYPosition: number;
bottomTPosition: number;
restartYPosition = 0;
@property scrollSpeed: number = 100;
invertedPosition = false;
start() {
if (!this.node.replicated) {
this.nodeHeight = this.node.getComponent(UITransform).height;
this.bottomNode = this.node;
this.upperNode = this.clone();
this.topYPosition = this.upperNode.getPosition().y;
this.bottomTPosition = this.bottomNode.getPosition().y - this.nodeHeight;
this.restartYPosition = -this.nodeHeight;
}
}
clone() {
const clone = instantiate(this.node);
clone.replicated = true;
const clonePosition = new Vec3(this.node.position.x, this.node.position.y + this.node.getComponent(UITransform).height);
clone.parent = this.node.parent;
clone.setPosition(clonePosition);
return clone;
}
scrollBackground(deltaTime: number) {
const upperNodeNewPosition = this.upperNode.position.y - this.scrollSpeed * deltaTime;
const gap = this.invertedPosition ? this.nodeHeight : - this.nodeHeight;
const bottomNodeNewPosition = upperNodeNewPosition + gap;
if (upperNodeNewPosition < this.restartYPosition) {
this.upperNode.setPosition(new Vec3(0, this.topYPosition, 0));
this.invertedPosition = false;
} else {
this.upperNode.setPosition(new Vec3(0, upperNodeNewPosition));
}
if (bottomNodeNewPosition < this.restartYPosition) {
this.bottomNode.setPosition(new Vec3(0, this.topYPosition, 0));
this.invertedPosition = true;
} else {
this.bottomNode.setPosition(new Vec3(0, bottomNodeNewPosition, 0));
}
}
update(deltaTime: number) {
if (!this.node.replicated) {
this.scrollBackground(deltaTime);
}
}
}