开始
  • 问题:不知道大家有没有这样一个需要,一张长地图你需要移动摄像机进行查看选择,等你选择进入其他场景后在退出发现摄像机位置归零。(注:本文中以摄像机X轴为零进行讲解)

    img_name

  • 思路:解决方案其实很简单,即存一个摄像机当前位置即可,在onLoad中进行赋值位置,可用两种方案。

    1. 存储为全局变量。应用退出后在进入摄像机位置归零,方便演示这里使用window全局变量,项目使用中可替换成自定义的全局变量。
    2. 存储在本地缓存中localStorage。除非清除缓存否则会每次进入上次停留位置
第一种全局变量方法
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


const {ccclass, property} = cc._decorator;

@ccclass
export default class CameraMove extends cc.Component {



// 摄像机最大往右移动数
private endBoundaryNum: number = 960;

public onLoad (): void {
this.isLocationX();
this.openTouch();
}
/**
* 判断有无摄像机位置,有则进行显示
* @private
*/
private isLocationX (): void {
// 全局模式记录位置,退出应用后再次打开即为0
let local_x = window['locationX'];
local_x ? this.node.x = local_x : 0;
}
/**
* 打开手指移动监听
*/
private openTouch (): void {
this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchStart, this);
}
/**
* 触摸移动开始
* @param event {cc.Event.EventTouch}
*/
private touchStart (event: cc.Event.EventTouch): void {
// event.getDeltaX() 获取触点距离上一次事件移动的 x 轴距离 右移动为负 左移为正
// 即当前x轴位置 - 移动距离
let x = this.node.x - event.getDeltaX();
// 判断x轴位置是否小于0或者是否大于最大右移位置
this.node.x = x <= 0 ? 0 : (x >= this.endBoundaryNum ? this.endBoundaryNum : x);
// 赋值全局变量
window['locationX'] = x;
}

}


第二种存入本地缓存中
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
const {ccclass, property} = cc._decorator;

@ccclass
export default class CameraMove extends cc.Component {
// 摄像机最大往右移动数
private endBoundaryNum: number = 960;

public onLoad (): void {
this.isLocationX();
this.openTouch();
}
/**
* 判断有无摄像机位置,有则进行显示
* @private
*/
private isLocationX (): void {
// 本地缓存模式记录位置,退出应用后再次打开为上次退出时位置
let local_x = localStorage.getItem('isLocationX');
local_x ? this.node.x = parseFloat(local_x) : 0;
}
/**
* 打开手指移动监听
*/
private openTouch (): void {
this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchStart, this);
}
/**
* 触摸移动开始
* @param event {cc.Event.EventTouch}
*/
private touchStart (event: cc.Event.EventTouch): void {
// event.getDeltaX() 获取触点距离上一次事件移动的 x 轴距离 右移动为负 左移为正
// 即当前x轴位置 - 移动距离
let x = this.node.x - event.getDeltaX();
// 判断x轴位置是否小于0或者是否大于最大右移位置
this.node.x = x <= 0 ? 0 : (x >= this.endBoundaryNum ? this.endBoundaryNum : x);
// 本地缓存添加
localStorage.setItem('isLocationX',x + '');
}

}

两种方案的区别主要在于下次打开应用是从零开始还是回到上次关闭前的位置,可以根据具体需求进行使用。

最终效果

img_name